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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Data-Mining

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值