Sometimes, we may want to get the file extension from a file path.
In this article, we’ll look at how to get the file extension from a path with JavaScript.
String.prototype.split
We can use the JavaScript string’s split
method to get the extension from a file path by getting the substring that’s after the last dot in the path.
For instance, we can write:
const ext = '/home/foo/bar.txt'.split('.').pop();
console.log(ext)
We call split
with the dot to split the string by the dot.
And then we call pop
on it to remove the last item from the split string and return it.
And so ext
is 'txt'
.
Regex Match
We can also match the file extension with Regex.
For instance, we can write:
const filename = '/home/foo/bar.txt'
const ext = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
console.log(ext)
We have the filename
with the file path.
Then we look for dots in the filename
string with exec
.
If there’re any dots in the string, then we check for anything that starts with a dot at the end of a string.
Dollar sign means at the end of the string.
And ^
means starts with.
This would be the file extension.
Therefore, we get the same result as before.
String.prototype.substring and String.prototype.lastIndexOf
We can use a string’s lastIndexOf
method to get the index of the last instance of a substring.
And we can combine that with the substring
method to extract the file extension substring.
For instance, we can write:
const filename = '/home/foo/bar.txt'
const ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length) || filename;
console.log(ext)
We call substring
with filename.lastIndexOf(‘.’) + 1
as the starting index.
And filename.length
is the end index.
Then ext
should be the same as the other value.
String.prototype.slice and String.prototype.lastIndexOf
We can use slice
instead of substring
to extract a substring from a JavaScript string.
Therefore, we can use it to get the file extension from a file path with it.
To use it, we write:
const filename = '/home/foo/bar.txt'
const ext = filename.slice((Math.max(0, filename.lastIndexOf(".")) || Infinity) + 1)
console.log(ext)
We find the max between index 0 and the index returned by lastIndexOf
to get the last index of the dot.
A path can start with a dot, so it’s possible that the index is 0.
Then we add 1 to get the index excluding the dot itself.
Therefore, we get the same result as we have before.
Conclusion
We can use various JavaScript string methods to extract the file extension from a string.