Extracting the extension from a filename string
A few months back I was building a plugin for Obsidian and needed to check the file extension of the file I was handling. In a moment of pure brain fart, I did it quite poorly, but luckily the good folks at Obsidian picked it up in my pull request and I was able to fix it.
How I did it
I was using JavaScript, and I approached it like this.
filename = 'picture.jpg'
filename.subStr(-3);
Why it’s a problem
There are several problems with the above code.
First, not all extensions are 3 characters —If the extension is longer, you’ll end up with just part of it. If it’s shorter, you’ll end up with parts that aren’t the extension.
Second, if the string passed into this is shorter than 3 characters, it will produce an error.
Another way
The below code splits the string into an array by any periods in it, then it pops the last item in the array off and returns it.
This ends up with the correct filename no matter the length.
filenameStr.split('.').pop();
A better way
The problem with the revised code is that still doesn’t handle a case where the filename has no extension.
We could build some if statements to add onto that but let’s approach it an entirely different way instead. Here’s a whole function:
function getExtension(filename: string): string | undefined {
const dotIndex = filename.lastIndexOf('.');
// Check there's a period
if (dotIndex !== -1) {
// return anything after the period
return filename.substring(dotIndex + 1);
}
// There was no period, so no extension
return undefined;
}
What does it handle
getExtension('picture.jpg') // 'jpg'
getExtension('picture.jpeg') // 'jpeg'
getExtension('picture') // undefined
getExtension('.gitignore') // 'gitignore'
That’s it!
Bear in mind that you’ll see plenty of other ways to achieve this. When you find one you like, you should post it to your own blog so you can find it again easily whenever you forget (That’s clearly what I do!).
Thanks…
I also dissect and speculate on design and development.
Digging into subtle details and implications, and exploring broad perspectives and potential paradigm shifts.
Check out my conceptual articles on Substack or find my latest below.
You can also find me on Threads, Bluesky, Mastodon, or X for more diverse posts about ongoing projects.
Leave a Reply