/**
* Removes the last file extension from a filename or path.
*
* Examples:
* "document.pdf" -> "document"
* "archive.tar.gz" -> "archive.tar"
* "photo.jpg" -> "photo"
* "README" -> "README"
* "/tmp/file.txt" -> "/tmp/file"
* ".gitignore" -> ".gitignore"
*
* Preserve hidden files: .gitignore should remain unchanged.
*
* @param {string} filePath - A filename or full path.
* @returns {string} The filename/path without its last extension.
* @throws {TypeError} If filePath is not a string.
*/
function removeFileExtension(filePath) {
if (typeof filePath !== "string") {
throw new TypeError("filePath must be a string.");
}
// Find the last path separator.
const lastSeparator = Math.max(
filePath.lastIndexOf("/"),
filePath.lastIndexOf("\\")
);
// Find the last dot.
const lastDot = filePath.lastIndexOf(".");
// No extension found.
if (lastDot === -1) {
return filePath;
}
// Handle hidden files such as ".gitignore".
if (lastDot <= lastSeparator + 1) {
return filePath;
}
// Return everything before the last extension.
return filePath.slice(0, lastDot);
}
// Example usage
console.log(removeFileExtension("document.pdf"));
console.log(removeFileExtension("archive.tar.gz"));
console.log(removeFileExtension("/tmp/file.txt"));
console.log(removeFileExtension(".gitignore"));
console.log(removeFileExtension("README"));
/*
run:
document
archive.tar
/tmp/file
.gitignore
README
*/