本文最后更新于:2023年8月24日 晚上
使用
功能:传递文件路径,获取其中的文件地址
一些例子:
1 2 3 4 5 6 7 8
| basename('D:\\static\\pages\\index.html') basename('D:/static/pages/index.html') basename('D:/static/pages/index') basename('../index.vue') basename('./../index.text.vue') basename('./../index.text.vue', false) basename('D:/static/pages/.git') basename()
|
basename.js
第一种写法:查找最后的分号后截取获取文件名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
export const basename = (path, suffix = true) => { if (!path) throw new Error('路径不可为空!') let index = path.lastIndexOf('/') index = index !== -1 ? index : path.lastIndexOf('\\') let fileName = path.substring(index + 1) if (suffix) return fileName const suffixIndex = fileName.lastIndexOf('.') if (suffixIndex !== -1) return fileName.substring(0, suffixIndex) return fileName }
|
第二种写法:使用正则直接获取文件名 ——by Kar
1 2 3 4 5 6 7 8 9
|
export const getFileName = (path, suffix = true) => (suffix ? /.*[/\\](.*?)$/ : /.*[/\\](.*?)\..*?$/).exec('/' + path)?.[1]
|
细节:最后匹配时添加/防止出现单文件名导致正则中正反斜杠匹配不上,帅就完事了