(rawValue: any, options: EscapeOptions = {})
| 31 | * for the complete original algorithm. |
| 32 | */ |
| 33 | export function escapeString(rawValue: any, options: EscapeOptions = {}) { |
| 34 | const { delimiter = '"', escapeChar = '\\', escapeNewlines = true } = options; |
| 35 | |
| 36 | const stringValue = rawValue.toString(); |
| 37 | |
| 38 | return [...stringValue] |
| 39 | .map(c => { |
| 40 | if (c === '\b') { |
| 41 | return `${escapeChar}b`; |
| 42 | } else if (c === '\t') { |
| 43 | return `${escapeChar}t`; |
| 44 | } else if (c === '\n') { |
| 45 | if (escapeNewlines) { |
| 46 | return `${escapeChar}n`; |
| 47 | } |
| 48 | return c; // Don't just continue, or this is caught by < \u0020 |
| 49 | } else if (c === '\f') { |
| 50 | return `${escapeChar}f`; |
| 51 | } else if (c === '\r') { |
| 52 | if (escapeNewlines) { |
| 53 | return `${escapeChar}r`; |
| 54 | } |
| 55 | return c; // Don't just continue, or this is caught by < \u0020 |
| 56 | } else if (c === escapeChar) { |
| 57 | return escapeChar + escapeChar; |
| 58 | } else if (c === delimiter) { |
| 59 | return escapeChar + delimiter; |
| 60 | } else if (c < '\u0020' || c > '\u007E') { |
| 61 | // Delegate the trickier non-ASCII cases to the normal algorithm. Some of these |
| 62 | // are escaped as \uXXXX, whilst others are represented literally. Since we're |
| 63 | // using this primarily for header values that are generally (though not 100% |
| 64 | // strictly?) ASCII-only, this should almost never happen. |
| 65 | return JSON.stringify(c).slice(1, -1); |
| 66 | } |
| 67 | return c; |
| 68 | }) |
| 69 | .join(''); |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Make a string value safe to insert literally into a snippet within single quotes, |
no outgoing calls
no test coverage detected
searching dependent graphs…