Get selected file extension in JavaScript

While working with files, sometimes we need to validate file extensions or get file extension for independent use like displaying file based on extensions. With HTML input, we can ask a user to upload a file to webpage.

Validating user input is necessary while file upload. It can be risky to enable user to upload all types of files to a server. For that, we can add client-side or server-side validation. But before implementing, we need to get and specify file extensions to enable upload.

In this tutorial, we will take file type input from user and display its extension using regex and split & pop method. Here, we will take examples of both methods.

Before starting let's add form and input with file type into our webpage. You can use existing forms or elements as per your requirement.

<form action="/fileupload.php">
    <input id="userFile" type="file" name="file">
    <button onclick="getExtension()">Get Extension</button>
</form>
<p id="displayExtension"></p>

Here, we have created a form and added input with file type. We have also added an empty paragraph tag with a unique id. In a further example, we will use this p tag to display the extension of a file.

Get File Extension Using Regex

The regex finds patterns in string and returns a response based on pattern. In files, name and extensions are divided by . and extensions can not contain any special characters. So we will define our regex based on this logic.

function getExtension() {
    var fileInput = document.getElementById('userFile');
    var fileName = fileInput.files[0].name;

    var pattern = /\.([0-9a-z]+)(?:[\?#]|$)/i;
    var fileExtension = (fileName).match(pattern);

    document.getElementById('displayExtension').innerText = fileExtension;
}
In the above example, we have to get file data using its ID. Then defined the regex pattern for finding the extension and matching it with file name. At last, we have displayed the extension to a user in an empty paragraph tag.

Get File Extension Using Split and Pop Method

In this method, we will use split() to split string into array with a dot. Then we will use pop() function to get last element from array which is an extension of a file.

Let's take an example to understand it.

function getExtension() {
    var fileInput = document.getElementById('userFile');
    var fileName = fileInput.files[0].name;

    var fileExtension = fileName.split('.').pop();

    document.getElementById('displayExtension').innerText = fileExtension;
}

Here, we'll get file name just like previous method. Then split name extension into array and display user extension which last element of array.

Conclusion

In this article, we have taken a simple example to get file extensions. This example will get you file extension. From now on you can use extensions for your requirement like validation or showing user messages or more.