[英]How can I extract the filename from a path?
The path from which I want to extract the filename takes the form: 我要从中提取文件名的路径采用以下形式:
C:\Folder1\Folder2\Folder3\Folder4\Folder5\x.png
This should give x (I do not need the extension). 这应该给x(我不需要扩展名)。 The file is always a PNG file.
该文件始终是PNG文件。 x can be 1, 2, 3 or 4 digits, but can never contain any other character (only a number).
x可以是1、2、3或4位数字,但不能包含任何其他字符(只能是数字)。
I tried a 'manual' method, which is working well. 我尝试了一种“手动”方法,该方法效果很好。
function getId(x) {
x = x.slice(0,-4);
var str = "";
var flag = 0;
for(var i = x.length - 1; i >= 0; i--) {
if(!isNaN(x[i])) {
str = x[i] + str;
flag = 1;
} else if(flag == 1) {
break;
}
}
console.log(str);
}
Is there any simpler approach without using a library? 有没有不使用库的更简单方法?
You could match one or more times a digit in a capturing group. 您可以在捕获组中将一个或多个数字匹配。 Then match a dot and not a backslash one or more times using a negated character class and assert the end of the string.
然后使用否定的字符类将一个点而不是反斜杠匹配一次或多次,并声明字符串的结尾。
const regex = /(\\d+)\\.[^\\\\]+$/; const str = "C:\\\\Folder1\\\\Folder2\\\\Folder3\\\\Folder4\\\\Folder5\\\\1.png"; console.log(str.match(regex)[1]);
You can use split()
and pop()
to get the file name without extension: 您可以使用
split()
和pop()
获得不带扩展名的文件名:
var file = 'C:\\\\Folder1\\\\Folder2\\\\Folder3\\\\Folder4\\\\Folder5\\\\x.png'; var fileName = file.split(/\\\\/).pop(); fileName = fileName.split('.')[0]; console.log(fileName);
Not the best way, but so simple: 不是最好的方法,但是很简单:
const str = 'C:\\Folder1\\Folder2\\Folder3\\Folder4\\Folder5\\t.png';
const getId = path => path.split('\\').pop().split('.')[0];
console.log(getId(str));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.