How to remove file extension in JavaScript

2 Answers

0 votes
/**
 * 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

*/

 



answered Oct 12 by avibootz
0 votes
const path = require("path");

/**
 * Removes the last extension from a filename or path.
 *
 * @param {string} filePath
 * @returns {string}
 */
function removeFileExtension(filePath) {
  const parsed = path.parse(filePath);

  return path.join(parsed.dir, parsed.name);
}

// 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

*/

 



answered Oct 12 by avibootz
...