Get File Extensions in JavaScript: 3 Easy Ways For You

Robin
Updated on October 8, 2022

No matter how complex the filenames are, You can get file extensions in JavaScript very easily. Using these extensions, you will understand what types of files your website is handling.

These are the 3 ways to get file extension from a filename in JavaScript:

  1. Using split() and pop() methods in JavaScript.
  2. Get file extensions with substring() and lastIndexOf() methods.
  3. Using regular expression (Regex) to find the file extension.

You can also these techniques to extract an extension from the selected file in the HTML <input> tag. In this way, it is possible to perform different file validation checks in JavaScript before uploading a file to the server.

After knowing one of the use cases of getting file extensions, let's see how to do this with some examples.

Using split() and pop() to Get File Extensions in JavaScript

JavaScript split() method converts a string to an array based on a separator. As we know, a file extension is a part followed by the dot (.) and attached to the end of a filename.

That's why we need to use the dot (.) as the separator while using the split() method. You will get the extension as a separate item inside the array.

          const filename = 'user.jpg';

const arr = filename.split('.');

console.log(arr);
// ['user', 'jpg']
        

When we call the split() method on the filename variable, it returns an array with the name of the file and its extension.

Now it's time to take that extension out of the array. We can use the pop() method to do this. Because this method not only removes the last item from an array but returns it as well.

          const filename = 'user.jpg';

const arr = filename.split('.');

const extension = arr.pop();

console.log(extension);
// jpg
        

When you call the pop() method on the arr array, it will return the last item which is the file extension.

But we are doing everything separately in multiple lines. You can chain these 2 methods together to make it one line.

          const filename = 'user.jpg';

const extension = filename.split('.').pop();

console.log(extension);
// jpg
        

If you want to extract the extensions from multiple filenames, you will repeat this process. But it's good to create a helper function without repeating the same code many times.

Let's create a getFileExtension() function that will receive the filename as its parameter.

          const getFileExtension = (filename) => {
    return filename.split('.').pop();
};

const imageExt = getFileExtension('user.jpg');
console.log(imageExt);
// jpg

const fileExt = getFileExtension('app.module.js');
console.log(fileExt);
// js
        

Now you can call this function as many times as you want. Each time it will return the extension from the filename you passed.

Also Read: Learn How to Get File Extensions in Node.js From Any Files

Get File Extensions Using substring() and lastIndexOf() Methods

In this technique, we will use substring() and lastIndexOf() methods in JavaScript. We need to apply these 2 methods together in order to get the file extension.

The substring() method extracts the part of a string between the start and end indexes. If you don't provide the end index, it will return up to the end of that string.

Therefore, we have to find the starting index of the extension to extract it from the filename. That's why we will use the lastIndexOf() method.

          const filename = 'user.jpg';

const index = filename.lastIndexOf('.');

console.log(index);
// 4
        

If you call this method on the filename string with the (.) as its parameter, it will return the last index value of the dot. As you can see, we have the extension after this dot.

Now you just have to pass this value to the substring() method to extract that part.

          const getFileExtension = (filename) => {
    return filename.substring(filename.lastIndexOf('.'));
};

const imageExt = getFileExtension('user.jpg');
console.log(imageExt);
// .jpg

const fileExt = getFileExtension('app.module.js');
console.log(fileExt);
// .js
        

I am getting the index and passing it to the substring() method inside this getFileExtension() function. I can get the extension by calling this function.

But in this case, you will get the extension with the dot because we are finding the last index of the dot.

If you wish to get just the extension without any dot, you can do that just by adding 1 to the last index value.

          const getFileExtension = (filename) => {
    return filename.substring(filename.lastIndexOf('.') + 1);
};

const imageExt = getFileExtension('user.jpg');
console.log(imageExt);
// jpg

const fileExt = getFileExtension('app.module.js');
console.log(fileExt);
// js
        

I am adding 1 to the index value to skip the dot (.) character from the extension name. The substring() method will grab everything after the last dot character from the filename.

JavaScript has indexOf() method to find the index value. In this case, it is not a good solution. Because this method returns the index of the first occurrence of a value.

          const filename = 'app.module.js';

const extension = filename.substring(filename.indexOf('.'));

console.log(extension);
// .module.js

        

It is giving everything after the first dot (.) without giving the file extension. We will not get the correct output from the indexOf() method.

Therefore, you have to use the lasIndexOf() with the substring() method to get file extensions in JavaScript.

Also Read: How to Find Files By Extension, Name, or Pattern in Node.js

Using Regular Expression (Regex) to Get File Extensions

You can use a regular expression to find the extension from a filename. For that, we have the match() method in JavaScript.

We can call this method on a string and pass a regular expression. It will find a substring that matches the regular expression from the main string.

          const getFileExtension = (filename) => {
    return filename.match(/[^.]+$/)[0];
};

const imageExt = getFileExtension('user.jpg');
console.log(imageExt);
// jpg

const fileExt = getFileExtension('app.module.js');
console.log(fileExt);
// js

        

The match() method returns an array with information about the matched substring. The first item in this array will be the matched value which is the extension in this example.

That's why we have to return the first item from that array by adding [0] at the end.

Also Read: Input VS Change VS Blur VS Focus - Differences of JavaScript Events

Get Uploaded File Extension in JavaScript

Before uploading a file to the server, a user needs to select it using the HTML <input> field. We should perform different validations for security.

But first, you need to get the extension from the selected file. I have a <input> field with type="file" inside my HTML file.

          <form>
    <input type="file" name="user" id="user">
    <button id="btn">Submit</button>
</form>
        

I will listen to the change event on this field so that whenever a user selects a file, I can get the extension from that file.

Inside the event callback function, you have access to the event object. You can get the filename from the target property in that object.

          const user = document.getElementById('user');

user.addEventListener('change', (event) => {
    const filename = event.target.files[0].name;

    const extension = filename.split('.').pop();
    console.log(extension);
    // jpg
});
        

When you have the filename, it is easy to get the extension. You can apply any of the previous methods. Here, I am doing it with the split() and pop() method.

If a user selects a file like image.jpg in this <input> field, this change event will fire and you will get the extension of that selected file.

Now you can use this extension to do file type validation in JavaScript to restrict a user to upload certain types of files.

Conclusion

It doesn't matter which method you choose to find the file extension, you will get the same result. I have explained 3 ways in this article so that you can compare multiple options.

But you are not limited to these 3 techniques only. JavaScript has many methods that you can combine to create your own process.

The methods I discussed in this post are easy and simple. You can get file extensions in JavaScript using any one of them in your project.

Related Posts