How can I get file extensions with JavaScript?

后端 未结 30 1845
终归单人心
终归单人心 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:02

    Fast and works correctly with paths

    (filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
    

    Some edge cases

    /path/.htaccess => null
    /dir.with.dot/file => null
    

    Solutions using split are slow and solutions with lastIndexOf don't handle edge cases.

提交回复
热议问题