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".

asked Feb 17, 2016 by anonymous

2 Answers

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 Mar 4, 2016 by Eric Z Ma (44,280 points)
//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';
}
answered Apr 28, 2016 by Gilbert Velez (140 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...