/** * replaces all occurences of something in a string * @param stringArg * @param searchPattern * @param replacementString */ export const replaceAll = (stringArg: string, searchPattern: string, replacementString: string) => { return stringArg.replace(new RegExp(searchPattern, 'g'), replacementString); }; /** * Custom implementation of strip-indent * Removes the minimum indentation from all lines */ const stripIndent = (str: string): string => { const lines = str.split('\n'); // Find the minimum indentation (ignoring empty lines) let minIndent = Infinity; for (const line of lines) { if (line.trim().length > 0) { const match = line.match(/^(\s*)/); if (match) { minIndent = Math.min(minIndent, match[1].length); } } } // If no indentation found, return original string if (minIndent === Infinity || minIndent === 0) { return str; } // Remove the minimum indentation from all lines return lines.map(line => { if (line.length >= minIndent) { return line.slice(minIndent); } return line; }).join('\n'); }; export interface INormalizeOptions { stripLeadingTrailingEmptyLines?: boolean; stripAllEmptyLines?: boolean; stripIndent?: boolean; normalizeNewline?: boolean; replaceTabs?: boolean; } /** * Normalizes a string * @param stringArg * @param options */ export const standard = (stringArg: string, options?: INormalizeOptions): string => { let result = stringArg; if (!options || options.stripIndent) { result = stripIndent(result); // fix indention } if (!options || options.normalizeNewline) { result = result.replace(/\r\n/g, '\n'); // fix newlines } if (!options || options.replaceTabs) { result = replaceAll(result, '\t/', ' '); // fix tabs } if (!options || options.stripLeadingTrailingEmptyLines) { result = result.replace(/^\s*[\r\n]/gm, '').replace(/\s*[\r\n]$/gm, ''); } if (!options || options.stripAllEmptyLines) { result = result.replace(/^\s*[\r\n]/gm, ''); } return result; };