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. At least there are 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, it sometimes becomes necessary to find the file extension. In this article we will discuss about 3 different procedures to find out if at all it’s a file and if it’s a file, what type it is.

Must Read: The Most Efficient jQuery Plugin to Upload Multiple Files

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.

var 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.

Syntax

string.lastIndexOf (searchvalue, start);

var 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.

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.

var phrase = “Home is where the Heart is”;
var 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.
var fileName, fileExtension;
fileName = ‘file.jpeg’;
fileExtension = fileName.split('.').pop();
console.log (fileExtension);

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)

The Markup with the Script

In the markup section, I have add three images, a PDF and an HTML file. Next, we will check the script.

<!DOCTYPE html>
<html>
<head>
    <title>3 ways to find the File Extension using jQuery and JavaScript</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
        
    <style>
        * { font-family:Verdana; font-size:13px; width:200px; }
        p {
            cursor:pointer;
            margin:5px 0;
            padding:2px;
            border:solid 1px #888;
        }
        #divFiles {
            font-weight:bold;
            padding-top:10px
        }
    </style>
</head>
<body>
    <h3>Click the list below to see the file type</h3>
    <div>
        
        <p>1) image1.png</p>
        <p>2) image2.jpeg</p>
        <p>3) image3.jpg</p>
        <p>4) AnnualReport.pdf</p>
        <p>5) Home.html</p>
        <p>6) No extension</p>
    </div>
    <div id="divFiles"></div>
</body>

<script>
    $('p').click(function(event) {

        var fileName, fileExtension;
        fileName = event.target.innerHTML;

        fileExtension = fileName.replace(/^.*\./, '');     // USING JAVASCRIPT REGULAR EXPRESSIONS.

        switch (fileExtension) {
            case 'png': case 'jpeg': case 'jpg':
                $('#divFiles').text('Image file, with an extension ' + fileExtension);
                break;
            case 'html': case 'htm':
                $('#divFiles').text('File type: ' + fileExtension);
            case 'pdf':
                $('#divFiles').text('File type: ' + fileExtension);
                break;
            default:
                $('#divFiles').text('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 →