40

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.

SoulieBaby
  • 5,405
  • 25
  • 95
  • 145

8 Answers8

95

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.

user113716
  • 318,772
  • 63
  • 451
  • 440
84

To get the file extension, I would do this:

var ext = file.split('.').pop();
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
  • 4
    +1 - Much nicer way of getting the extension. Wish I'd thought of it! – user113716 Jun 15 '10 at 03:42
  • Yep.. neat. though I changed it to `file.name.split('.').pop()` because my var `file` is an object. Thanks! – kriscondev Apr 26 '17 at 02:15
  • 1
    the script will not work correctly when having query-string parameters, e.g. `/example/image.jpg?a=b&b=2`, to handle it i added one more splits `file.split("?")[0].split('.').pop()` (note: a lot of times systems used query-string to prevent cache when needed) – Roy Shoa Nov 20 '17 at 10:25
17

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
  • 33,305
  • 16
  • 69
  • 121
10

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 
rahul
  • 184,426
  • 49
  • 232
  • 263
3
var fileName = 'file.txt';

// Getting Extension

var ext = fileName.split('.')[1];

// OR

var ext = fileName.split('.').pop();
Amr SubZero
  • 1,196
  • 5
  • 19
  • 30
1

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
  • 11,462
  • 10
  • 53
  • 87
1

Try this:

var extension = fileString.substring(fileString.lastIndexOf('.') + 1);
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
0

Another way (which avoids extended switch-case statements) is to define arrays of file extensions for similar processing and use a function to check the extension result against an array (with comments):

// Define valid file extension arrays (according to your needs)
var _docExts = ["pdf", "doc", "docx", "odt"];
var _imgExts = ["jpg", "jpeg", "png", "gif", "ico"];
// Checks whether an extension is included in the array
function isExtension(ext, extnArray) {
    var result = false;
    var i;
    if (ext) {
        ext = ext.toLowerCase();
        for (i = 0; i < extnArray.length; i++) {
            if (extnArray[i].toLowerCase() === ext) {
                result = true;
                break;
            }
        }
    }
    return result;
}
// Test file name and extension
var testFileName = "example-filename.jpeg";
// Get the extension from the filename
var extn = testFileName.split('.').pop();
// boolean check if extensions are in parameter array
var isDoc = isExtension(extn, _docExts);
var isImg = isExtension(extn, _imgExts);
console.log("==> isDoc: " + isDoc + " => isImg: " + isImg);
// Process according to result: if(isDoc) { // .. etc }
RickL
  • 3,318
  • 10
  • 38
  • 39