How can I get file extensions with JavaScript?

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

    For most applications, a simple script such as

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

    would work just fine (as provided by Tom). However this is not fool proof. It does not work if the following file name is provided:

    image.jpg?foo=bar
    

    It may be a bit overkill but I would suggest using a url parser such as this one to avoid failure due to unpredictable filenames.

    Using that particular function, you could get the file name like this:

    var trueFileName = parse_url('image.jpg?foo=bar').file;
    

    This will output "image.jpg" without the url vars. Then you are free to grab the file extension.

提交回复
热议问题