Get selected file extension in JavaScript

Get File Extension in JavaScript is essential when working with file uploads or displaying files based on their type. Sometimes, you need to validate file extensions or extract them for further processing. HTML input allows users to upload files to a webpage, but handling them safely requires knowing their extensions.

Validating user input is crucial during file uploads to prevent unwanted file types from reaching the server. You can implement client-side or server-side validation, but first, you need to get and specify file extensions. In this tutorial, we will show how to extract file extensions using both regex and the split & pop method with practical examples.

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.

You can give users a quick view of uploaded images by showing a preview before submission. For practical examples, check out our post on Show Image Preview using jQuery.