3 ways to find the File Extension using JavaScript and jQuery

← PrevNext →

Dealing with files can be cumbersome since you will have to manage them using server side scripts. However, there are easy ways to find the type or extension of the files you are dealing with, using client side scripts like JavaScript and jQuery.

Before doing anything with the files and its contents on a web application, it sometimes becomes necessary to find the file extension. In this article we will discuss about 3 different procedures to find out if its actually a file and if it's a file, what type it is.

You may also like this: The jQuery plugin you'll need to upload Multiple files efficiently

01) Using JavaScript String “replace()” Method with Regular Expression Meta Characters

The replace() method usually replaces a value in a string with another set of given values. The general syntax for this method is: string.replace(searchvalue, newvalue).

Now how can this help us find the extension of the file?

The above method takes two parameters to replace values of a given string. In this case the string will be the filename itself and the first parameter will be the entire filename till the last “dot” and the second parameter will be a blank string.

Regular Expression Meta Characters will be used to fetch all the characters till the dot is found in the string. So these characters will be replaced with a blank string, leaving the file extension as the result.

let fileName, fileExtension;
fileName = 'file.jpeg';
fileExtension = fileName.replace(/^.*\./, '');
console.log (fileExtension);

Meta Characters can be confusing, so it needs to be explained. The characters “^.*” indicates, all characters. The character combination “\.” indicates till it reaches the “dot”. Putting together it means “get all the characters in the string, till it finds the “dot”. And this combination is written inside the 2 forward slash “/” at the beginning and at the end.


02) Using JavaScript String “substr ()” and “lastIndexOf()” Methods

Combining the 2 JavaScript methods will also return the file extension. The substr() method will extract or fetch certain values from a string.

The general syntax is: string.substr(start, length).

The first parameter start, will be a numeric value and second parameter “length” too accepts a numeric value.

The lastIndexOf() method will search for a particular string or character in the entire string and locate the position of the given string or character. It too returns a numeric value.


string.lastIndexOf (searchvalue, start);

let fileName, fileExtension;
fileName = 'file.jpeg';
fileExtension = fileName.substr((fileName.lastIndexOf('.') + 1));
console.log (fileExtension);

The .lastIndexOf() will find the location of the dot and return a numeric value plus 1, and this numeric value will be used by the method .substr() to return the remaining strings left.

In the above example the dot is at the 5th location and the .substr() will extract characters starting from 5 + 1 i.e., the 6th position and return jpeg.

03) Using JavaScript .split() and .pop() Methods

The JavaScript .split() method returns an array of words (separated by a comma) by splitting a string.


string.split(separator, limit);

The first parameter can be any character used to split the string and the second parameter is a numeric value defining the number of items returned as an arrays.

Let us assume, we have a string Home is where the Heart is and we’ll use this with the method.

let phrase = "Home is where the Heart is";
let Hm = phrase.split(' ', 2);

The result will be Home,is in the form of an array. It has returned 2 words from the string. Now try the .split() method by removing the value 2 and see the result.

The .pop() method will return the last item from an array of values but cannot be used directly with the string. So it has to be used with the .split() method.
let fileName, fileExtension;
fileName = 'file.jpeg';
fileExtension = fileName.split('.').pop();
console.log (fileExtension);
Try this example

While searching for the file extension (based on the character dot), the .split() method will split the string “file.jpeg” into two different items in an array, that is, file and jpeg. The .pop() method will return the last item, that is jpeg. (see example)

Here's an example (using replace() method with regular expressions)

In the markup section, I have added three images, a PDF and an HTML file. Now, let's check the script.

<!DOCTYPE html>
    <title>Check file extension using JavaScript</title>
    <h2>Select a file (any file) to check its extension.</h2>
    	<input type='file' onchange='uploadFile(this)'>
    <div id='theFile'></div>

    function uploadFile(fileUpload) {

    function checkFileExt (file) {
       let fileExtension;
        // Using regular expression.
        fileExtension = file.replace(/^.*\./, ''); 

        let ele = document.getElementById('theFile');
        switch (fileExtension) {
            case 'png': case 'jpeg': case 'jpg':
                ele.innerHTML = 'Image file, with an extension ' + fileExtension;
            case 'html': case 'htm':
                ele.innerHTML = 'File type: ' + fileExtension;
            case 'json': case 'pdf': case 'xml':
                ele.innerHTML = 'File type: ' + fileExtension;
                ele.innerHTML = 'File type: Unknown';
Try it

In the above examples I have used JavaScript Regular Expresssions to show how to find file extensions. You can try with the remaining 2 procedures and see if the results are the same. The methods I have discussed here can also be used for various other validations. It actually demonstrates how we can simplify our task using these methods.

← PreviousNext →