问题
I have a full path to an image, which I am using jquery to read, in the form $('img.my_image').attr('src') however I just want the filename portion (discarding the path).
Are there any built-in functions to do this, or would a regex be the only option?
回答1:
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
回答2:
var Filename= path.split('/').pop()
回答3:
function getFileName(path) {
return path.match(/[-_\w]+[.][\w]+$/i)[0];
}
回答4:
I found a better version handling unix and windows-like path-strings.
Number 1:
var unix_path = '/tmp/images/cat.jpg';
console.log(unix_path.replace(/^.*[\\\/]/, ''));
var win_path = 'c:\\temp\images\cat.jpg';
console.log(win_path.replace(/^.*[\\\/]/, ''));
Output will be cat.jpg
Number 2: (maybe faster)
var unix_path = '/tmp/images/cat.jpg';
console.log(unix_path.split(/[\\\/]/).pop());
var win_path = 'c:\\temp\images\cat.jpg';
console.log(win_path.split(/[\\\/]/).pop());
Output will be cat.jpg
回答5:
In Javascript you could do
function getFileNameFromPath(path) {
var ary = path.split("/");
return ary[ary.length - 1];
}
回答6:
Using this solution you can get both names i.e. with and without file extension.
//getting image source
var path=$('img.my_image').attr('src');
//splitting url and getting filename with file extension
var file=path.split('/').pop();
//removing extension and keeping just the filename
var filename=file.split('.').shift();
来源:https://stackoverflow.com/questions/2526061/getting-just-the-filename-from-a-path-with-javascript