( input: string, alwaysQuote: boolean = true, escapeNonAscii: boolean = false, )
| 797 | } |
| 798 | |
| 799 | export function escapeIdentifier( |
| 800 | input: string, |
| 801 | alwaysQuote: boolean = true, |
| 802 | escapeNonAscii: boolean = false, |
| 803 | ): string | null { |
| 804 | if (input == null) { |
| 805 | return null; |
| 806 | } |
| 807 | |
| 808 | let body = input.replace(SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => { |
| 809 | if (match[0] == '\n') { |
| 810 | return '\\n'; |
| 811 | } else if (match[0] == '\r') { |
| 812 | return '\\r'; |
| 813 | } else { |
| 814 | return `\\${match[0]}`; |
| 815 | } |
| 816 | }); |
| 817 | |
| 818 | const requiresQuotes = alwaysQuote || !LEGAL_IDENTIFIER_RE.test(body); |
| 819 | if (!requiresQuotes) { |
| 820 | return body; |
| 821 | } |
| 822 | |
| 823 | if (escapeNonAscii) { |
| 824 | body = body.replace(NON_ASCII_OR_CONTROL_CHAR_RE, (c, offset, str) => { |
| 825 | const code = c.charCodeAt(0); |
| 826 | if (code === 0) { |
| 827 | const next = str.charCodeAt(offset + 1); |
| 828 | return next >= 48 /* '0' */ && next <= 57 /* '9' */ ? '\\x00' : '\\0'; |
| 829 | } |
| 830 | return ( |
| 831 | CONTROL_CHAR_ESCAPES.get(c) ?? '\\u' + code.toString(16).toUpperCase().padStart(4, '0') |
| 832 | ); |
| 833 | }); |
| 834 | } |
| 835 | |
| 836 | return `'${body}'`; |
| 837 | } |
no test coverage detected