How to Get the File Extension from a Filename String
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
- Converting a number to a string with commas in JavaScript
- Merging several strings into one in JavaScript
- How to remove the last character from a string in JavaScript
- How to create and decode a query string in JavaScript