How to get file extension in JavaScript?

How to get file extension from a file name in JavaScript?

For examples,

For “file.txt”, I want to get “txt”.
For “file2.multi.ext.fileext”, I want to get “fileext”.

This JavaScript function works well for me.

function getExt(filename)
{
    var idx = filename.lastIndexOf('.');
    // handle cases like, .htaccess, filename
    return (idx < 1) ? "" : filename.substr(idx + 1);
}

It handles situations that the filename has no extensions like “.htaccess” and “filename”.

Answered by Eric Z Ma.

//This is fine if you know that there will be a nothing but a file name in "fileName" 
function getExt(fileName){
     return (fileName.lastIndexOf('.') < 1) ?   null : fileName.split('.').slice(-1);
}

//this is better for unexpected path data like: "/weird.folder/somefolder"
function getExt(path){
    return (path.match(/(?:.+..+[^\/]+$)/ig) != null) ? path.split('.').slice(-1): 'null';
}

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *