Explain Codes LogoExplain Codes Logo

How to extract extension from filename string in Javascript?

javascript
regex
functions
promises
Anton ShumikhinbyAnton Shumikhin·Dec 7, 2024
TLDR

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.

let filename = "example.png"; let extension = filename.slice(filename.lastIndexOf('.') + 1); console.log(extension); // Outputs: png

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.

let filename = "archive.tar.gz"; let extension = filename.slice(filename.lastIndexOf('.') + 1); console.log(extension); // Outputs: gz

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.

let regex = /(?:\.([^.]+))?$/; let filename = "archive.tar.gz"; let matches = regex.exec(filename); let extension = matches ? matches[1] : ''; console.log(extension); // Outputs: gz

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.

let filename = "my.report_2023.xlsx"; let extension = filename.split('.').pop(); console.log(extension); // Outputs: xlsx. Just like magic.

Using lastIndexOf()

lastIndexOf() can also be our navigational lighthouse, guiding us to the safe shores of the desired file extension.

let filename = "photo.jpg"; let extension = filename.substring(filename.lastIndexOf('.') + 1); console.log(extension); // Outputs: jpg. Click.

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?

// No extension let filename = "README"; let extension = filename.includes('.') ? filename.slice(filename.lastIndexOf('.') + 1) : ''; console.log(extension); // Outputs: (empty string), similar to my coffee cup on Monday mornings. // Dot-prefixed file filename = ".vimrc"; extension = filename.slice((filename[0] === '.' ? 1 : 0) + filename.lastIndexOf('.')); console.log(extension); // Outputs: vimrc. Isn't it simple? // Directory path handling filename = "/path/to/folder/"; extension = filename[filename.length - 1] === '/' ? '' : filename.split('.').pop(); console.log(extension); // Outputs: (empty string). It was a folder!

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!

let extensionWithDot = filename.lastIndexOf('.') !== -1 ? filename.slice(filename.lastIndexOf('.')) : ''; console.log(extensionWithDot); // Outputs: .png. Say hello to our dot friend!

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!

function getExtension(filename) { return filename.slice((filename.lastIndexOf(".") + 1) || filename.length); } console.log(getExtension("file_with_extension.docx")); // Outputs: docx console.log(getExtension("no_extension_file")); // Outputs: (empty string)

Paths: we've got your back!

With file paths, bear in mind that the file might be a directory or have additional path elements:

function getExtensionFromPath(path) { let baseName = path.split('/').pop(); // pop makes filename extraction a breeze! if(baseName.indexOf('.') === -1 || baseName[0] === '.') return ''; // no extension? no worries! return baseName.slice(baseName.lastIndexOf('.') + 1); // voila, there's your extension! } console.log(getExtensionFromPath("/path/to/file.txt")); // Outputs: txt console.log(getExtensionFromPath("/path/without/extension/file")); // Outputs: (empty string), because honestly, there's no extension.