How can I get file extensions with JavaScript?

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

    0 讨论(0)
  • 2020-11-22 10:01
    var extension = fileName.substring(fileName.lastIndexOf('.')+1);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:02
    var file = "hello.txt";
    var ext = (function(file, lio) { 
      return lio === -1 ? undefined : file.substring(lio+1); 
    })(file, file.lastIndexOf("."));
    
    // hello.txt -> txt
    // hello.dolly.txt -> txt
    // hello -> undefined
    // .hello -> hello
    
    0 讨论(0)
  • 2020-11-22 10:03

    Wallacer's answer is nice, but one more checking is needed.

    If file has no extension, it will use filename as extension which is not good.

    Try this one:

    return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';
    
    0 讨论(0)
提交回复
热议问题