How to get file extension in JavaScript?
Posted on In QAHow 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”.
//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';
}
Here I have written similar article 2 ways to get file extension https://codepedia.info/get-file-extension-javascript/ . Hope your readers find it useful