Saturday, February 23, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...