How can I get file extensions with JavaScript?
To extract a file extension in JavaScript, simply split the string from the last dot:
This quick piece of code finds the last dot in a filename and retrieves everything after it, which is typically the file extension.
Edge cases and their treatment
In life, as in JavaScript, it's not always plain sailing. There might be multiple dots in the filename or even hidden files that start with a dot. Fret not, let's sail these waters with some effective JS code.
Consider the following methods to handle these troublesome cases:
Breaking the split habit
Performance junkies out there, I see you! You're thinking, "Can I skip creating an array just for a simple thing?" Here's your serving of substring and lastIndexOf:
The regex spell
For those who want precision and are intrigued by the wizardry of regular expressions, here's a spell to fine-tune the extension extraction:
Zoom zoom, this one is faster?
One file extension extraction method to rule them all? Benchmarking is your answer.
- The split-pop method: Short and sweet for short filenames.
- Substring-lastIndexOf: Best for long journeys - I mean, long filenames.
- Regular expressions: When you need your magic wand but might be slower.
Advanced file naming conventions
Welcome to level 2: you've got versions or filenames with multiple extensions to deal with. We know, this is where we separate the wheat from the chaff. Let's move.
Was this article helpful?