How can I get file extensions with JavaScript?

后端 未结 30 1743
终归单人心
终归单人心 2020-11-22 09:37

See code:

var file1 = \"50.xsl\";
var file2 = \"30.doc\";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExt         


        
相关标签:
30条回答
  • 2020-11-22 10:09

    Newer Edit: Lots of things have changed since this question was initially posted - there's a lot of really good information in wallacer's revised answer as well as VisioN's excellent breakdown


    Edit: Just because this is the accepted answer; wallacer's answer is indeed much better:

    return filename.split('.').pop();
    

    My old answer:

    return /[^.]+$/.exec(filename);
    

    Should do it.

    Edit: In response to PhiLho's comment, use something like:

    return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
    
    0 讨论(0)
  • 2020-11-22 10:09

    Don't forget that some files can have no extension, so:

    var parts = filename.split('.');
    return (parts.length > 1) ? parts.pop() : '';
    
    0 讨论(0)
  • 2020-11-22 10:11
    function getFileExtension(filename)
    {
      var ext = /^.+\.([^.]+)$/.exec(filename);
      return ext == null ? "" : ext[1];
    }
    

    Tested with

    "a.b"     (=> "b") 
    "a"       (=> "") 
    ".hidden" (=> "") 
    ""        (=> "") 
    null      (=> "")  
    

    Also

    "a.b.c.d" (=> "d")
    ".a.b"    (=> "b")
    "a..b"    (=> "b")
    
    0 讨论(0)
  • 2020-11-22 10:12
    return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
    

    edit: Strangely (or maybe it's not) the $1 in the second argument of the replace method doesn't seem to work... Sorry.

    0 讨论(0)
  • 2020-11-22 10:13

    If you are dealing with web urls, you can use:

    function getExt(filepath){
         return filepath.split("?")[0].split("#")[0].split('.').pop();
    }
    
    getExt("../js/logic.v2.min.js") // js
    getExt("http://example.net/site/page.php?id=16548") // php
    getExt("http://example.net/site/page.html#welcome.to.me") // html
    getExt("c:\\logs\\yesterday.log"); // log
    

    Demo: https://jsfiddle.net/squadjot/q5ard4fj/

    0 讨论(0)
  • 2020-11-22 10:14
    function getExt(filename)
    {
        var ext = filename.split('.').pop();
        if(ext == filename) return "";
        return ext;
    }
    
    0 讨论(0)
提交回复
热议问题