How to extract extension from filename string in Javascript?
To extract the extension from a filename, you can use String.prototype.slice()
and String.prototype.lastIndexOf()
. This finds the position of the final period and slices off the substring after it, which then becomes the extension.
This handles filenames with multiple periods, slicing off everything after the last period, since that's where the real magic (i.e., the file extension) lives.
If no extension is present? No problem – it simply returns an empty string.
Detailed explanation with regex
Regular Expressions (Regex) provide a more flexible approach, easily handling filenames with multiple extensions or those without any extension at all.
Here in this regex:
(?: )
spawns a non-capturing group to match the dot but not capture it. It's not that we don't like dots, we just don't need it here.([^.]+)
is a capturing group to match any character apart from a dot, one or more times.?
makes the whole group optional, effectively handling situations where the file is extensionless!$
is an anchor to the end of the string, because that's where file extensions live (in a nice cozy home right at the end).
This way, we've got all grounds covered – simple filenames, double extensions, or even those without any extension.
A dive into versatile methods
There's no one-size-fits-all in programming. So let's learn a few more methods, each fit for different scenarios.
Using split and pop
You can extract the extension by splitting the filename using .
as the delimiter and popping out the last fragment.
Using lastIndexOf()
lastIndexOf()
can also be our navigational lighthouse, guiding us to the safe shores of the desired file extension.
Handling special cases
Files with dot prefixes (like .htaccess
), filenames without an extension, or directory paths are not uncommon. We meet these in the real world, don't we?
Including the dot
If your format requires including the dot with the extension, adjust the slice method slightly. Just slice from the position of the last period!
Functions and fun along the way
To adopt modularity and reuse in our techniques, let's wrap one of our methods into a nice little function. This way, we can harvest file extensions anytime, anywhere!
Paths: we've got your back!
With file paths, bear in mind that the file might be a directory or have additional path elements:
Was this article helpful?