* Escapes a string for use in a Python double-quoted string literal. * Handles backslashes, quotes, control characters, and non-printable characters.
(str: string)
| 268 | * Handles backslashes, quotes, control characters, and non-printable characters. |
| 269 | */ |
| 270 | function escapeString(str: string): string { |
| 271 | return ( |
| 272 | str |
| 273 | .replace(/\\/g, '\\\\') // Backslash must be first |
| 274 | .replace(/"/g, '\\"') // Double quotes |
| 275 | .replace(/\n/g, '\\n') // Newline |
| 276 | .replace(/\r/g, '\\r') // Carriage return |
| 277 | .replace(/\t/g, '\\t') // Tab |
| 278 | // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally matching backspace character |
| 279 | .replace(/[\x08]/g, '\\b') // Backspace (use hex to avoid \b word boundary) |
| 280 | // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally matching form feed character |
| 281 | .replace(/[\x0C]/g, '\\f') // Form feed (use hex to avoid literal control char) |
| 282 | // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally matching control characters for escaping |
| 283 | .replace(/[\x00-\x07\x0B\x0E-\x1F\x7F-\x9F]/g, char => { |
| 284 | // Escape other control characters as \uXXXX |
| 285 | const code = char.charCodeAt(0) |
| 286 | return `\\u${code.toString(16).padStart(4, '0')}` |
| 287 | }) |
| 288 | ) |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Escapes content for use in a Python raw triple-quoted string (r"""). |
no outgoing calls
no test coverage detected