@stryke/path
Version:
A package containing various utilities that expand the functionality of NodeJs's built-in `path` module
44 lines (42 loc) • 1.69 kB
JavaScript
import { cwd } from "./cwd.mjs";
import { slash } from "./slash.mjs";
import { isParentPath } from "./is-parent-path.mjs";
import { findFileDotExtensionSafe, findFileExtensionSafe } from "./file-path-fns.mjs";
//#region src/replace.ts
/**
* Replace the base path from the beginning of the given path.
*
* @example
* ```ts
* replacePath("/home/user/project/src/index.ts", "/home/user/project");
* // returns "src/index.ts"
* ```
*
* @param childPath - The child path to replace the {@link parentPath} substring from
* @param parentPath - The parent path to remove from the {@link childPath} parameter
* @returns The {@link childPath} with the {@link parentPath} path removed
*/
function replacePath(childPath, parentPath = cwd()) {
return isParentPath(childPath, parentPath) ? slash(childPath).replace(slash(parentPath), "").replace(/^\//, "") : childPath;
}
/**
* Replace the extension of a given path with the provided value.
*
* @example
* ```ts
* replaceExtension("/home/user/project/src/index.ts", ".js");
* // returns "/home/user/project/src/index.js"
* replaceExtension("/home/user/project/src/index.ts");
* // returns "/home/user/project/src/index"
* ```
*
* @param path - The path that will have its current extension replaced
* @param replacement - The value (or an empty string) to replace the current extension with
* @returns The path with the replaced extension
*/
function replaceExtension(path, replacement = "", options) {
return path.replace(!replacement || replacement.includes(".") ? findFileDotExtensionSafe(path, options) : findFileExtensionSafe(path, options), replacement);
}
//#endregion
export { replaceExtension, replacePath };
//# sourceMappingURL=replace.mjs.map