Getting just the filename from a path with Javascript

亡梦爱人 提交于 2019-12-17 17:46:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!