1.如何检验字符串文件扩展名、域名后缀等

书诚小驿2024/12/24前端知识库JavaScript

前言

在前端开发中,检验字符串是否以特定的后缀(如文件扩展名、域名后缀)结束是一个常见的需求。应用场景常见的有文件上传验证、表单校验,URL 处理等

1、检验example.comcom后缀

let a = "example.com".split(".").pop().toLowerCase();
consoel.log(a); // true
let b = "example.cn".split(".").pop().toLowerCase();
consoel.log(b); // false
  • .split('.') 将字符串安装.分割成多个部分
  • .pop()从列表中移除并返回最后一个元素
  • .toLowerCase() 将返回的字符串转换为小写

2、检验example.com.com后缀

let a = "example.com".endswith(".com");
console.log(a); // true
let b = "example.cn".endswith(".com");
console.log(b); // false
  • .endswith() 方法是 es6 引入的,检验字符串是否以指定的后缀结束

3、校验上传的文件类型是否为视频格式上传

let resA = "example.jpg";
let resB = "example.mp4";
function isVideoFile(filePath) {
  const videoExtensions = [
    "mp4",
    "avi",
    "mov",
    "mkv",
    "webm",
    "flv",
    "wmv",
    "vob",
    "mpg",
    "mpeg",
  ];
  const fileExtension = filePath.split(".").pop().toLowerCase();
  return videoExtensions.includes(fileExtension);
}
console.log(isVideoFile(resA)); // false
console.log(isVideoFile(resB)); // true
最后更新时间' 2025/1/3 14:16:58