Phillnet-2 / Tools /utils /textUtils.ts
ayjays132's picture
Upload 478 files
101858b verified
/**
* Safely replaces the first occurrence of a literal string within a text.
* Throws if the string is not found or is ambiguous.
*/
export function safeLiteralReplace(text: string, oldStr: string, newStr: string): string {
const index = text.indexOf(oldStr);
if (index === -1) {
throw new Error(`Target content not found in file.`);
}
const lastIndex = text.lastIndexOf(oldStr);
if (index !== lastIndex) {
throw new Error(`Target content is ambiguous (multiple occurrences found). Please provide more context.`);
}
return text.substring(0, index) + newStr + text.substring(index + oldStr.length);
}
/**
* Normalizes line endings to LF.
*/
export function normalizeLineEndings(text: string): string {
return text.replace(/\r\n/g, '\n');
}
/**
* Truncates text with an ellipsis if it exceeds a maximum length.
*/
export function truncateText(text: string, maxLength: number): string {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
}