How to get File Extension using JavaScript
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
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.
1 2 3 4 5 6 7 8 9 10 11 | // 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.
1 2 3 4 5 6 7 8 9 10 11 | // 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..!! 🙂