extract extension from filename in javascript

You can use the lastIndexOf method to find the last occurrence of the dot (.) character in the string, which would indicate the start of the file extension. Then you can use the substring method to extract the file extension from the file name.

Here's an example code:

index.tsx
const fileName = "example.docx";
const extensionIndex = fileName.lastIndexOf(".");
const extension = fileName.substring(extensionIndex + 1);
console.log(extension); // Output: "docx"
183 chars
5 lines

In this example code, lastIndexOf method returns the index of the last occurrence of the "." character in the file name, which is 7 in this case. Then we add 1 to this index and pass it as the starting index for the substring method. The substring method returns the part of the file name after the "." character, which is the file extension "docx" here.

gistlibby LogSnag