How can I get file extensions with JavaScript?

后端 未结 30 2422
终归单人心
终归单人心 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;
    

提交回复
热议问题