How to remove file extension in TypeScript

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"
 *
 * @param filePath The filename or full path.
 * @returns The filename/path without its last extension.
 * @throws TypeError If filePath is empty.
 */
function removeFileExtension(filePath: string): string {
    if (filePath.trim().length === 0) {
        throw new TypeError("filePath cannot be empty.");
    }

    // Find the last path separator.
    const lastSeparator: number = Math.max(
        filePath.lastIndexOf("/"),
        filePath.lastIndexOf("\\")
    );

    // Find the last dot.
    const lastDot: number = 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.substring(0, lastDot);
}

// Example usage
const file1: string = "document.pdf";
const file2: string = "archive.tar.gz";
const file3: string = "/tmp/file.txt";
const file4: string = ".gitignore";
const file5: string = "README";

console.log(removeFileExtension(file1));
console.log(removeFileExtension(file2));
console.log(removeFileExtension(file3));
console.log(removeFileExtension(file4));
console.log(removeFileExtension(file5));



/*
run:

document
archive.tar
/tmp/file
.gitignore
README

*/

 



answered Oct 12 by avibootz
0 votes
import * as path from "path";

/**
 * Removes the last file extension from a filename or path.
 */
function removeFileExtension(filePath: string): string {
    const parsed: path.ParsedPath = path.parse(filePath);

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


// Example usage
const file1: string = "document.pdf";
const file2: string = "archive.tar.gz";
const file3: string = "/tmp/file.txt";
const file4: string = ".gitignore";
const file5: string = "README";

console.log(removeFileExtension(file1));
console.log(removeFileExtension(file2));
console.log(removeFileExtension(file3));
console.log(removeFileExtension(file4));
console.log(removeFileExtension(file5));



/*
run:

document
archive.tar
/tmp/file
.gitignore
README

*/

 



answered Oct 12 by avibootz
...