Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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*/ } 
like image 310
Sergio del Amo Avatar asked Oct 10 '08 11:10

Sergio del Amo


People also ask

What is the file extensions of JavaScript files?

JavaScript files have the file extension .js.

How do I create a .js file extension?

To create a Js (JavaScript) file simply remove the SCRIPT tags and save the JavaScript code with a . js extension using Notepad. This allows you to call the JavaScript when needed, instead of having the JavaScript code typed out in the HTML (Hyper Text Markup Language) code.

How do I get the file extension of an input type file?

The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string. By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.


1 Answers

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; 
like image 61
5 revs Avatar answered Oct 03 '22 11:10

5 revs