How can I get file extensions with JavaScript?

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

提交回复
热议问题