Javascript – How to get file extensions with JavaScript

file extensionjavascript

See code:

var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExtension(filename) {
    /*TODO*/
}

Best Answer

Newer Edit: Lots of things have changed since this question was initially posted - there's a lot of really good information in wallacer's revised answer as well as VisioN's excellent breakdown


Edit: Just because this is the accepted answer; wallacer's answer is indeed much better:

return filename.split('.').pop();

My old answer:

return /[^.]+$/.exec(filename);

Should do it.

Edit: In response to PhiLho's comment, use something like:

return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;