How can I get file extensions with JavaScript?

后端 未结 30 1740
终归单人心
终归单人心 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:06
    var parts = filename.split('.');
    return parts[parts.length-1];
    
    0 讨论(0)
  • 2020-11-22 10:06

    i just wanted to share this.

    fileName.slice(fileName.lastIndexOf('.'))
    

    although this has a downfall that files with no extension will return last string. but if you do so this will fix every thing :

       function getExtention(fileName){
         var i = fileName.lastIndexOf('.');
         if(i === -1 ) return false;
         return fileName.slice(i)
       }
    
    0 讨论(0)
  • 2020-11-22 10:07

    The following solution is fast and short enough to use in bulk operations and save extra bytes:

     return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
    

    Here is another one-line non-regexp universal solution:

     return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);
    

    Both work correctly with names having no extension (e.g. myfile) or starting with . dot (e.g. .htaccess):

     ""                            -->   ""
     "name"                        -->   ""
     "name.txt"                    -->   "txt"
     ".htpasswd"                   -->   ""
     "name.with.many.dots.myext"   -->   "myext"
    

    If you care about the speed you may run the benchmark and check that the provided solutions are the fastest, while the short one is tremendously fast:

    Speed comparison

    How the short one works:

    1. String.lastIndexOf method returns the last position of the substring (i.e. ".") in the given string (i.e. fname). If the substring is not found method returns -1.
    2. The "unacceptable" positions of dot in the filename are -1 and 0, which respectively refer to names with no extension (e.g. "name") and to names that start with dot (e.g. ".htaccess").
    3. Zero-fill right shift operator (>>>) if used with zero affects negative numbers transforming -1 to 4294967295 and -2 to 4294967294, which is useful for remaining the filename unchanged in the edge cases (sort of a trick here).
    4. String.prototype.slice extracts the part of the filename from the position that was calculated as described. If the position number is more than the length of the string method returns "".

    If you want more clear solution which will work in the same way (plus with extra support of full path), check the following extended version. This solution will be slower than previous one-liners but is much easier to understand.

    function getExtension(path) {
        var basename = path.split(/[\\/]/).pop(),  // extract file name from full path ...
                                                   // (supports `\\` and `/` separators)
            pos = basename.lastIndexOf(".");       // get last position of `.`
    
        if (basename === "" || pos < 1)            // if file name is empty or ...
            return "";                             //  `.` not found (-1) or comes first (0)
    
        return basename.slice(pos + 1);            // extract extension ignoring `.`
    }
    
    console.log( getExtension("/path/to/file.ext") );
    // >> "ext"
    

    All three variants should work in any web browser on the client side and can be used in the server side NodeJS code as well.

    0 讨论(0)
  • 2020-11-22 10:07

    I'm many moons late to the party but for simplicity I use something like this

    var fileName = "I.Am.FileName.docx";
    var nameLen = fileName.length;
    var lastDotPos = fileName.lastIndexOf(".");
    var fileNameSub = false;
    if(lastDotPos === -1)
    {
        fileNameSub = false;
    }
    else
    {
        //Remove +1 if you want the "." left too
        fileNameSub = fileName.substr(lastDotPos + 1, nameLen);
    }
    document.getElementById("showInMe").innerHTML = fileNameSub;
    <div id="showInMe"></div>

    0 讨论(0)
  • 2020-11-22 10:07

    "one-liner" to get filename and extension using reduce and array destructuring :

    var str = "filename.with_dot.png";
    var [filename, extension] = str.split('.').reduce((acc, val, i, arr) => (i == arr.length - 1) ? [acc[0].substring(1), val] : [[acc[0], val].join('.')], [])
    
    console.log({filename, extension});

    with better indentation :

    var str = "filename.with_dot.png";
    var [filename, extension] = str.split('.')
       .reduce((acc, val, i, arr) => (i == arr.length - 1) 
           ? [acc[0].substring(1), val] 
           : [[acc[0], val].join('.')], [])
    
    
    console.log({filename, extension});
    
    // {
    //   "filename": "filename.with_dot",
    //   "extension": "png"
    // }
    
    0 讨论(0)
  • 2020-11-22 10:08
    function file_get_ext(filename)
        {
        return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
        }
    
    0 讨论(0)
提交回复
热议问题