How can I get file extensions with JavaScript?

后端 未结 30 2423
终归单人心
终归单人心 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 09:59

    There is a standard library function for this in the path module:

    import path from 'path';
    
    console.log(path.extname('abc.txt'));
    

    Output:

    .txt

    So, if you only want the format:

    path.extname('abc.txt').slice(1) // 'txt'
    

    If there is no extension, then the function will return an empty string:

    path.extname('abc') // ''
    

    If you are using Node, then path is built-in. If you are targetting the browser, then Webpack will bundle a path implementation for you. If you are targetting the browser without Webpack, then you can include path-browserify manually.

    There is no reason to do string splitting or regex.

提交回复
热议问题