How to get File Extension using JavaScript
📅May 3, 2022
Today you will learn how to get file extension from given file name using JavaScript. Here we will see two different methods to get the file extension. You may need it during File Upload or Preview Image.
Checkout more articles on JavaScript
- How to swap two array elements in JavaScript
- How to clear an HTML file input using JavaScript
- Reverse a String in JavaScript
- How to check if an array is empty or exist in JavaScript
Way to get file extension using JavaScript
1. Using split() and pop() method
Let’s use the split() and pop() methods to split the string and get the last element.
// get file extension
function getFileExtension(filename){
const extension = filename.split('.').pop();
return extension;
}
const res1 = getFileExtension('index.html');
console.log(res1); // Output: html
const res2 = getFileExtension('index.txt');
console.log(res2); // Output: txt
2. Using substring() and lastIndexOf() method
In this second method, we’ll use the substring() and lastIndexOf() to get the file extension.
// get file extension
function getFileExtension(filename){
const extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
return extension;
}
const res1 = getFileExtension('index.html');
console.log(res1); // Output: html
const res2 = getFileExtension('index.txt');
console.log(res2); // Output: txt
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂