How to Get File Extensions with JavaScript

File extensions play a crucial role in determining the type of file and the software that can open it.

As a developer, you might come across situations where you need to extract the file extension of a file.

This Javascript tutorial will guide you on how to get the file extension of a file in JavaScript.


Using split() and pop()

The simplest method to get the file extension is by using the split() and pop() functions in JavaScript.

The split() function is used to split a string into an array of substrings and the pop() function is used to remove the last element of the array.

Code Example:

let filename = "example.txt";
let fileArray = filename.split(".");
let fileExtension = fileArray.pop();
console.log(fileExtension); // Output: txt

Using substr()

Another method to get the file extension is by using the substr() function in JavaScript.

The substr() function is used to extract a part of a string.

Code Example:

let filename = "example.txt";
let lastDotIndex = filename.lastIndexOf(".");
let fileExtension = filename.substr(lastDotIndex + 1);
console.log(fileExtension); // Output: txt

Using Regular Expressions

Regular expressions can also be used to get the file extension in JavaScript.

Regular expressions are a powerful tool for pattern matching and string manipulation.

Code Example:

let filename = "example.txt";
let fileExtension = filename.match(/\.[^.]+$/)[0];
console.log(fileExtension); // Output: .txt

Conclusion

In this tutorial, we learned how to get the file extension of a file in JavaScript.

We saw three different methods to achieve this, using split() and pop(), substr(), and Regular expressions.

You can choose the method that suits your needs and requirements.

I hope this tutorial was helpful in understanding the concepts and I would love to hear your feedback in the comments section below.