Getting just the filename from a path with JavaScript

前端 未结 6 554
醉话见心
醉话见心 2020-12-08 04:56

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

相关标签:
6条回答
  • 2020-12-08 05:01
    var Filename= path.split('/').pop()
    
    0 讨论(0)
  • 2020-12-08 05:03
    function getFileName(path) {
    return path.match(/[-_\w]+[.][\w]+$/i)[0];
    }
    
    0 讨论(0)
  • 2020-12-08 05:07

    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();
    
    
    0 讨论(0)
  • 2020-12-08 05:09

    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

    0 讨论(0)
  • 2020-12-08 05:19

    In Javascript you could do

    function getFileNameFromPath(path) {
      var ary = path.split("/");
      return ary[ary.length - 1];
    }
    
    0 讨论(0)
  • 2020-12-08 05:23
    var fileNameIndex = yourstring.lastIndexOf("/") + 1;
    var filename = yourstring.substr(fileNameIndex);
    
    0 讨论(0)
提交回复
热议问题