How can I get file extensions with JavaScript?

后端 未结 30 2213
终归单人心
终归单人心 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: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")
    

提交回复
热议问题