Replaces a file extension with another one.
npx @tessl/cli install tessl/npm-replace-ext@2.0.0Replace Ext is a lightweight utility function that replaces file extensions in path strings while preserving directory structure and handling cross-platform path separators. It's designed for build tools, file processing utilities, and applications that need to transform file paths by changing their extensions.
npm install replace-extconst replaceExt = require('replace-ext');const replaceExt = require('replace-ext');
// Replace extension in a simple filename
const newPath = replaceExt('file.js', '.ts');
console.log(newPath); // file.ts
// Replace extension in a full path
const fullPath = replaceExt('/some/dir/file.coffee', '.js');
console.log(fullPath); // /some/dir/file.js
// Remove extension entirely
const noExt = replaceExt('document.pdf', '');
console.log(noExt); // document
// Preserves relative path structure
const relativePath = replaceExt('./src/index.js', '.ts');
console.log(relativePath); // ./src/index.tsReplaces the file extension in a path string with a new extension while preserving directory structure and handling edge cases.
/**
* Replaces the extension from npath with ext and returns the updated path string.
* Does not replace the extension if npath is not a string or is empty.
*
* @param {string} npath - The file path whose extension should be replaced
* @param {string} ext - The new extension (including the dot, e.g., '.js')
* @returns {string|*} The path with the new extension, or original input if not a string
*/
function replaceExt(npath, ext);Key Features:
./ and ../ in relative pathsUsage Examples:
const replaceExt = require('replace-ext');
// Basic extension replacement
replaceExt('test.coffee', '.js'); // 'test.js'
replaceExt('/path/to/file.ts', '.js'); // '/path/to/file.js'
// Extension removal
replaceExt('document.pdf', ''); // 'document'
replaceExt('/docs/readme.md', ''); // '/docs/readme'
// Adding extension to extensionless file
replaceExt('/path/to/file', '.txt'); // '/path/to/file.txt'
// Relative path handling
replaceExt('./src/index.js', '.ts'); // './src/index.ts'
replaceExt('../lib/util.coffee', '.js'); // '../lib/util.js'
// Safe input handling
replaceExt(null, '.js'); // null (unchanged)
replaceExt('', '.js'); // '' (unchanged)
replaceExt({}, '.js'); // {} (unchanged)Cross-platform Behavior:
The function handles path separators correctly across different operating systems:
// On Windows
replaceExt('a\\b\\c.js', '.ts'); // 'a\\b\\c.ts'
replaceExt('.\\a\\b\\c.js', '.ts'); // '.\\a\\b\\c.ts'
// On Unix/Linux/macOS
replaceExt('a/b/c.js', '.ts'); // 'a/b/c.ts'
replaceExt('./a/b/c.js', '.ts'); // './a/b/c.ts'