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
catIn 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
gzCommon mistake
split('.').pop() returns the whole name when there is no dot:
console.log('README'.split('.').pop());Output:
READMEFunctions used in this recipe
- String.prototype.lastIndexOf — Finds the last occurrence of a text in a string.
- String.prototype.slice — Returns part of a string.