How to Remove a File Extension from a String in JavaScript
When working with filenames, a common task is to remove the file extension to get the "base name" of the file (e.g., converting "report.pdf" to "report"). The best method for this depends on your runtime environment: Node.js has a powerful, purpose-built module for this, while in the browser, you must use standard string manipulation methods.
This guide will demonstrate the robust, recommended method for Node.js using the path module, and the best browser-compatible method using String.prototype.lastIndexOf() and slice().
In Node.js (Recommended): The path Module
If your code is running in a Node.js environment, the built-in path module is the best and most reliable tool for any path manipulation. It is designed to correctly handle edge cases, different operating systems, and complex paths.
The logic: the path.parse() method takes a path string and returns an object with its components (dir, base, ext, and name). The name property is exactly what we need: the filename without the extension.
The solution:
import path from 'path'; // For ES Modules
// const path = require('path'); // For CommonJS
function getBaseName(filePath) {
return path.parse(filePath).name;
}
// Example Usage:
console.log(getBaseName('C:\\Users\\Test\\document.pdf')); // Output: document
console.log(getBaseName('archive.tar.gz')); // Output: archive.tar
console.log(getBaseName('filename-without-extension')); // Output: filename-without-extension
The path.parse() method is smart enough to handle multiple dots, correctly identifying .gz as the extension in archive.tar.gz.
In the Browser: lastIndexOf() and slice()
In a browser environment, you do not have access to the path module. The most common and readable "vanilla JS" method is to find the index of the last dot in the string and "slice" the string up to that point.
Problem: you need a browser-compatible way to remove the extension from a filename string.
// Problem: Get "report" from "report.pdf".
const filename = 'report.pdf';
Solution:
function removeExtension(filename) {
// Find the last dot in the filename
const lastDotIndex = filename.lastIndexOf('.');
// If there's no dot, or if it's the first character (e.g., ".env"),
// return the original filename.
if (lastDotIndex === -1 || lastDotIndex === 0) {
return filename;
}
// Slice the string from the beginning up to the last dot.
return filename.slice(0, lastDotIndex);
}
// Example Usage:
console.log(removeExtension('image.jpeg')); // Output: image
console.log(removeExtension('archive.tar.gz')); // Output: archive.tar
console.log(removeExtension('.config')); // Output: .config
console.log(removeExtension('nodot')); // Output: nodot
How the Browser Method Works
filename.lastIndexOf('.'): This method searches the string for the.character, starting from the end, and returns its zero-based index. If no dot is found, it returns-1.- Edge Case Check:
if (lastDotIndex === -1 || lastDotIndex === 0)handles two cases:lastDotIndex === -1: No extension was found.lastDotIndex === 0: The file is a "dotfile" (like.gitignore), which is generally considered to have no extension.
filename.slice(0, lastDotIndex):slice()extracts a section of the string. By slicing from the beginning (0) up to the index of the last dot, we effectively chop off the extension.
An Alternative Browser Method: Regular Expressions
You can also use a regular expression with String.prototype.replace() to remove the extension. This method is more concise but can be less readable for developers unfamiliar with regex.
Solution:
function removeExtensionRegex(filename) {
// The regex replaces a dot and any characters after it at the end of the string.
return filename.replace(/\.[^/.]+$/, '');
}
// Example Usage:
console.log(removeExtensionRegex('image.jpeg')); // Output: image
console.log(removeExtensionRegex('archive.tar.gz')); // Output: archive.tar
Observe that:
\.: Matches a literal dot.[^/.]+: Matches one or more characters that are not a dot or a forward slash.$: Anchors the match to the end of the string.
While powerful, the lastIndexOf and slice method is often easier to read and understand.
Conclusion
Removing a file extension is a simple task, but the best tool depends on your environment.
- If you are in a Node.js environment, the
path.parse(filePath).namemethod is the overwhelmingly recommended best practice. It is robust, reliable, and purpose-built for path manipulation. - If you are in a browser environment, the combination of
lastIndexOf('.')andslice()is the clearest and most common solution.