How to Get the File Extension from a Filename String

OpenJavaScript 0

Last updated: December 28, 2022.

It can often be useful to extract the extension from a filename stored in a string.

For this, you can use the slice() method. This method slices a string between two indexes, passed in as two arguments.

To slice a string to get the file extension, you can set the first argument value to the last apperance of "." in the string using lastIndexOf(). This returns its index position.

To omit the dot, add 1 to the first argument value.

Then, set the second argument to the value of length of the string to include all characters until the end of the string:

const filename = "image.png";

const res = filename.slice(filename.lastIndexOf(".") + 1, filename.length);

console.log(res); // png

Related posts