Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get a file extension

Short answer

In Node.js, extname() from node:path returns the extension with the dot:

import { extname, basename } from 'node:path';
 
console.log(extname('photos/cat.jpeg'));
console.log(basename('photos/cat.jpeg'));
console.log(basename('photos/cat.jpeg', '.jpeg'));

Output:

.jpeg
cat.jpeg
cat

In the browser

Without node:path, take everything after the last dot. A name without a dot has no extension:

const getExtension = (name) => {
  const dot = name.lastIndexOf('.');
  return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
};
 
console.log(getExtension('Report.PDF'));
console.log(getExtension('archive.tar.gz'));
console.log(getExtension('README'));
console.log(getExtension('.gitignore'));

Output:

pdf
gz

Common mistake

split('.').pop() returns the whole name when there is no dot:

console.log('README'.split('.').pop());

Output:

README

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.