* Safely replace all occurrences of a literal string, handling $ escape sequences. * Standard String.replaceAll treats $ specially in the replacement string. * This function ensures literal replacement. * * @param str The original string * @param oldString The string to replace * @param newStr
(str: string, oldString: string, newString: string)
| 52 | * @returns The string with all occurrences replaced |
| 53 | */ |
| 54 | function safeLiteralReplace(str: string, oldString: string, newString: string): string { |
| 55 | if (oldString === "" || !str.includes(oldString)) { |
| 56 | return str |
| 57 | } |
| 58 | |
| 59 | // If newString doesn't contain $, we can use replaceAll directly |
| 60 | if (!newString.includes("$")) { |
| 61 | return str.replaceAll(oldString, newString) |
| 62 | } |
| 63 | |
| 64 | // Escape $ to prevent ECMAScript GetSubstitution issues |
| 65 | // $$ becomes a single $ in the output, so we double-escape |
| 66 | const escapedNewString = newString.replaceAll("$", "$$$$") |
| 67 | return str.replaceAll(oldString, escapedNewString) |
| 68 | } |
| 69 | |
| 70 | function detectLineEnding(content: string): LineEnding { |
| 71 | return content.includes("\r\n") ? "\r\n" : "\n" |