> 文档中心 > 根据后端返回的路径后缀名不同渲染对应图标、图片、require、exec、split、toLowerCase

根据后端返回的路径后缀名不同渲染对应图标、图片、require、exec、split、toLowerCase

目录


版本一

function file(data) {// 需要渲染的图片let imgPath = {txt: require('@/image/txt.jpg'),mp4: 'image/MP4.png',gif: require('@/image/GIF.png'),jpg: 'image/jpg.png',png: require('@/image/png.jpg'),docx: 'image/docx.png',// 默认图标defaultImg: require('@/image/defaultImg.jpg'),};// /\.[a-zA-Z]+/.exec(data)[0] 获取后缀名,包括 .// split('.')[1] 去除后缀名的 .// toLowerCase() 转小写let path = imgPath[/\.[a-zA-Z]+/.exec(data)[0].split('.')[1].toLowerCase()];  // 当对象中找不到和传入的后缀名匹配时,  // 使用默认图片  data = path == undefined ? imgPath.defaultImg : path;// 返回对应的图片路径return data;};console.log(file('http://youdao.GIF'));// image/GIF.pngconsole.log(file('http://Word.docx'));// image/docx.pngconsole.log(file('http://baidu.png'));// image/png.jpgconsole.log(file('http://viod.mp3'));// image/defaultImg.jpg

版本二

/* * 根据文件后缀名渲染对应图标 * @param {object} fileName 路径/地址 * @return {object} 该函数会返回一个图片字符串 */function fileSuffixName(fileName = "") {  // 需要渲染的图片  let imgPath = {      // 图片的引入方式为require('@/image/txt.jpg')最佳      txt: "../image/text.png",      mp3: "../image/mp3.png",      mp4: "../image/mp4.png",      gif: "../image/gif.png",      jpg: "../image/jpg.png",      png: "../image/png.png",      docx: "../image/docx.png",      // 默认图标      defaultImg: "../image/defaultImg.png",    },    path = null,    // 判断是否有点    reg = /\.[a-zA-Z]+/.exec(fileName);  if (reg) {    // /\.[a-zA-Z]+/.exec(fileName)[0] 获取后缀名,包括点(.)    // split('.')[1] 去除后缀名的点(.)    // toLowerCase() 转小写    path = imgPath[reg[0].split(".")[1].toLowerCase()];  } else {    path = imgPath[fileName.toLowerCase()];  }  // 当对象中找不到和传入的后缀名匹配时,  // 使用默认图片  fileName = !path ? imgPath.defaultImg : path;  // 返回对应的图片路径  return fileName;}console.log(fileSuffixName("http://youdao.GIF"));// ../image/gif.pngconsole.log(fileSuffixName("http://Word.docx"));// ../image/docx.pngconsole.log(fileSuffixName("mp3"));// ../image/mp3.pngconsole.log(fileSuffixName("DOCX"));// ../image/docx.pngconsole.log(fileSuffixName("-"));// ../image/defaultImg.pngconsole.log(fileSuffixName(""));// ../image/defaultImg.pngconsole.log(fileSuffixName());// ../image/defaultImg.png