I have a full path to an image, which I am using jQuery to read like this:
$(\'img.my_image\').attr(\'src\');
However I just want the f
var Filename= path.split('/').pop()
function getFileName(path) {
return path.match(/[-_\w]+[.][\w]+$/i)[0];
}
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();
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
In Javascript you could do
function getFileNameFromPath(path) {
var ary = path.split("/");
return ary[ary.length - 1];
}
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);