Getting File Extensions in JavaScript
Extracting a file extension from a filename is a common task. Here are the main approaches, with modern best practices. Simple Method with lastIndexOf() The most straightforward approach uses lastIndexOf() to find the last dot: function getExtension(filename) { const lastDotIndex = filename.lastIndexOf(‘.’); return (lastDotIndex < 1) ? ” : filename.substring(lastDotIndex + 1); } console.log(getExtension(‘file.txt’)); //…
