Explain Codes LogoExplain Codes Logo

How can I get file extensions with JavaScript?

javascript
file-extensions
javascript-functions
performance-optimization
Nikita BarsukovbyNikita Barsukov·Jan 18, 2025
TLDR

To extract a file extension in JavaScript, simply split the string from the last dot:

const extension = 'example.png'.split('.').pop(); console.log(extension); // Outputs: 'png'

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:

function getFileExtension(filename) { // If there's no party, leave. Also, hidden files don't party. if (!filename.includes('.') || filename[0] === '.') return ''; // Now, get the party popper let extension = filename.split('.').pop(); // Remember, 'PNG' and 'png' are not the same guest. return extension.toLowerCase(); }

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:

const getExtension = (filename) => { let lastIndex = filename.lastIndexOf('.'); // Boom! Dot is shy or doesn't exist. if (lastIndex < 1) return ''; // There you go! You've got your invite. return filename.substring(lastIndex + 1).toLowerCase(); };

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:

const regex = /(?:\.([^.]+))?$/; const extension = regex.exec('example.png')[1]; // 'png'

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.

const multipleExtensionHandler = (filename) => { // Is there a basename in the house? let filenameOnly = path.basename(filename); // Party hasn't started until after the first dot. return filenameOnly.split('.').pop(); }