How to get file extensions using JavaScript ?
To extract file extensions using JavaScript, there are several effective methods such as:
Using split() and pop() method:
This method breaks the filename into two parts: the name and the extension. The extension is then retrieved by popping the last element of the array.
Example :
let fileName = 'document.txt';
let extension = fileName.split('.').pop(); // Returns 'txt'
Using substring() and lastIndexOf() method:
The substring method fetches a portion of the string starting from the index found by the lastIndexOf() method, which locates the period(.) in the filename.
Example:
let fileName = 'document.txt';
let extension = fileName.substring(fileName.lastIndexOf('.') + 1); // Returns 'txt'
Using match() method with Regular Expression:
This method uses a regular expression to find and extract the file extension. It matches everything after the period(.) in the filename.
Example :
let fileName = 'document.txt';
let regex = /[^.]+$/;
let extension = fileName.match(regex); // Returns 'txt'
We have various method to get the file extension.
Keep Learning 🙂