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.

01) Using JavaScript string "replace()" Method with Regular Expression Meta Characters

The replace() method replaces a value in a string with another set of given values.

.replace() method syntax

string.replace(searchvalue, newvalue)

The method takes two parameters to replace values of a given string.

searchvalue: the value or the string to search.

newvalue: the value or string with which the search value will be replaced.

The string in our example, will be the "filename" and the first parameter will be the entire filename till the last “dot”.
The second parameter is a blank string.

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

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.

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

Using "substr()" and "lastIndexOf()" methods together will also return the file extension.

substr() method Syntax

string.substr(start, length).

The substr() method will extract or fetch certain values from a string.

The first parameter start, will be a numeric value and second parameter "length" also accepts a numeric value.

lastIndexOf() method Syntax

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 to get file extensions

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

Syntax

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);
console.log (Hm);    // Ouput: ["Home", "is"]

It 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>
<html>
<head>
    <title>Check file extension using JavaScript</title>
</head>
<body>
    <h2>Select a file (any file) to check its extension.</h2>
    <p>
    	<input type='file' onchange='uploadFile(this)'>
    </p>
    
    <div id='theFile'></div>
</body>

<script>
    function uploadFile(fileUpload) {
        checkFileExt(fileUpload.value);
    }

    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;
                break;
            case 'html': case 'htm':
                ele.innerHTML = 'File type: ' + fileExtension;
                break;
            case 'json': case 'pdf': case 'xml':
                ele.innerHTML = 'File type: ' + fileExtension;
                break;
            default:
                ele.innerHTML = 'File type: Unknown';
        }
    }
</script></html>
Try it
Conclusion

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 →