views:

61

answers:

6

Hi all, 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.

+1  A: 

Since the extension will always be the string after a period in a complete/partial file name, just use the built in split function in js, and test the resultant extension for what you want it to do. If split returns only one piece / no pieces, it does not contain an extension.

futureelite7
+1  A: 
rahul
+4  A: 

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.

patrick dw
Haha, I almost left a comment, then I thought Hmm... maybe I am not understanding something. +1 great answer
Doug Neiner
+1  A: 

Try this:

var extension = fileString.substring(fileString.lastIndexOf('.') + 1);
Jacob Relkin
+7  A: 

To get the file extension, I would do this:

var ext = file.split('.').pop();
Doug Neiner
+1 - Much nicer way of getting the extension. Wish I'd thought of it!
patrick dw
+3  A: 

Yet another way to write it up:

function getExtension(filename) {
    return filename.split('.').pop().toLowerCase();
}

function openFile(file) { 
    switch(getExtension(file)) {
        //if .jpg/.gif/.png do something
        case 'jpg': case 'gif': case 'png':
            /* handle */
            break;
        //if .zip/.rar do something else
        case 'zip': case 'rar':
            /* handle */
            break;

        //if .pdf do something else
        case 'pdf':
            /* handle */
            break;
    }
}
artlung
+1 for adding `.toLowerCase()`. Could be important.
patrick dw