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!).

I’d love to know if any of these articles helped you.
Share what you’re building or ask me a question on Threads or somewhere else.

Instagram is a great place to see my final creative coding experiments, while the others are are great place to connect or see progress updates.

If my content has helped you, I’d never say no to donations to help me keep writing.

Here are some other things you might like


Author:

Date:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.