JavaScript(JS) JS get file extension

To get the file extension of a file path or name in JavaScript, you can use the built-in String methods such as split() or substring(). Here are a few examples:

Example 1: Using split() method

const filePath = 'myFile.txt';
const fileExtension = filePath.split('.').pop();
console.log(fileExtension); // Output: txt
Source:w‮itfigi.ww‬dea.com

In this example, we use the split() method to split the filePath string into an array based on the . separator. We then use the pop() method to retrieve the last item in the array, which corresponds to the file extension.

Example 2: Using substring() method

const filePath = 'path/to/myFile.docx';
const fileExtension = filePath.substring(filePath.lastIndexOf('.') + 1);
console.log(fileExtension); // Output: docx

In this example, we use the substring() method to extract the file extension from the filePath string. We start by finding the index of the last occurrence of the . separator using the lastIndexOf() method. We then add 1 to the index to get the start index of the file extension, and pass this value to the substring() method to extract the remaining characters of the string.

Note that both of these methods assume that the file path or name contains only one . separator, and that the extension is located after the last . separator. If your file path or name contains multiple . separators, you may need to modify these methods accordingly.