Get selected file extension in JavaScript

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

Validating user input is necessary during file upload. It can be risky to enable users 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 a 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 requirements.

<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 a pattern. In files, names 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;
}

Get File Extension Using Split and Pop Method

In this method, we will use split() to split a string into an array with a dot. Then we will use the pop() function to get the last element from an 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 the file name just like the previous method. Then split name extension into an array and display the user extension which last element of an array.

Conclusion

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