Saturday 23 February 2019

How can I get file extensions with JavaScript?




See code:



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

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


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;

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...