Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find file extension (from string)

Tags:

jquery

file

I was wondering if it was possible for jQuery to find a file extension based on a returned string?

A filename (string) will be passed to a function (openFile) and I wanted that function to do different things based on what file has been passed through, it could be image files or pdf files.

function openFile(file) {     //if .jpg/.gif/.png do something    //if .zip/.rar do something else    //if .pdf do something else  }; 

I've been looking for something that will find the file's extension but I can't seem to find anything.

like image 741
SoulieBaby Avatar asked Jun 15 '10 03:06

SoulieBaby


People also ask

How to find extension of file in jQuery?

function openFile(file) { var extension = file. substr( (file. lastIndexOf('.

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.


2 Answers

How about something like this.

Test the live example: http://jsfiddle.net/6hBZU/1/

It assumes that the string will always end with the extension:

function openFile(file) {     var extension = file.substr( (file.lastIndexOf('.') +1) );     switch(extension) {         case 'jpg':         case 'png':         case 'gif':             alert('was jpg png gif');  // There's was a typo in the example where         break;                         // the alert ended with pdf instead of gif.         case 'zip':         case 'rar':             alert('was zip rar');         break;         case 'pdf':             alert('was pdf');         break;         default:             alert('who knows');     } };  openFile("somestring.png"); 

EDIT: I mistakenly deleted part of the string in openFile("somestring.png");. Corrected. Had it in the Live Example, though.

like image 163
user113716 Avatar answered Oct 09 '22 07:10

user113716


To get the file extension, I would do this:

var ext = file.split('.').pop(); 
like image 45
Doug Neiner Avatar answered Oct 09 '22 09:10

Doug Neiner