JS文件名和路径截取分割

常用方法有两种

以/Users/lz/project/test.txt为例分别介绍一下

方法一、

fullPath = '/Users/lz/project/test.txt';
pos = fullPath.lastIndexOf('/');
fileName = fullPath.substr(pos+1);
console.log(fileName);
filePath = fullPath.substr(0,pos);
console.log(filePath);

但是这种方法有一个缺点是,如果遇到windows路径字符串就会一脸蒙圈,需要区分平台类型采取不同的编码策略,比如:

// windows平台路径
fullPath = 'C:\\project\\test.txt';
pos = fullPath.lastIndexOf('\\');
fileName = fullPath.substr(pos+1);
console.log(fileName);
filePath = fullPath.substr(0,pos);
console.log(filePath);

这样处理的话就需要知道平台类型,有没有可以不需要判断平台类型的方法呢?答案是有的。我们在只需要在操作之前就行格式化处理。 

// 自己声明一个replaceAll方法
String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

fullPath = '/Users/lz/project/test.txt';
fileName = 'test.txt';
fullPath = fullPath.replaceAll('/', '\\');
console.log(fullPath);
pos = fullPath.lastIndexOf('\\');
fileName = fullPath.substr(pos+1);
console.log(fileName);
filePath = fullPath.substr(0,pos);
console.log(filePath);

方法二、

如果你已经知道文件名,那就更好办了。

fullPathMac = '/Users/lz/project/test.txt';
fullPathWin = 'C:\\project\\test.txt';
fileName = 'test.txt';
filePath = fullPathMac.replace(fileName, '');
console.log(filePath);
filePath = fullPathWin.replace(fileName, '');
console.log(filePath);

猜你喜欢

转载自blog.csdn.net/liuzehn/article/details/106005657