(text: string, regexLiterals?: number[])
| 38 | * closing `/` of every span read as a regex literal (left as is). |
| 39 | */ |
| 40 | export function blankStringContents(text: string, regexLiterals?: number[]): string { |
| 41 | // Blanked runs are spaces, and the text between them is copied by the |
| 42 | // slice, as BlankedText does for the strippers. |
| 43 | const parts: string[] = []; |
| 44 | let copied = 0; |
| 45 | const blank = (start: number, end: number): void => { |
| 46 | if (end <= start) return; |
| 47 | parts.push(text.slice(copied, start), ' '.repeat(end - start)); |
| 48 | copied = end; |
| 49 | }; |
| 50 | let i = 0; |
| 51 | const n = text.length; |
| 52 | while (i < n) { |
| 53 | const c = text[i]!; |
| 54 | // A quote inside a JS regex is data, not the beginning of a string. |
| 55 | // Expression-start punctuation and keywords distinguish these from division. |
| 56 | if (c === '/' && REGEX_START_BEFORE.test(text.slice(Math.max(0, i - 32), i))) { |
| 57 | let end = i + 1; |
| 58 | let inClass = false; |
| 59 | for (; end < n && text[end] !== '\n'; end++) { |
| 60 | if (text[end] === '\\') { end++; continue; } |
| 61 | if (text[end] === '[') inClass = true; |
| 62 | if (text[end] === ']') inClass = false; |
| 63 | if (text[end] === '/' && !inClass) break; |
| 64 | } |
| 65 | if (end < n && text[end] === '/') { |
| 66 | regexLiterals?.push(i, end); |
| 67 | i = end + 1; |
| 68 | continue; |
| 69 | } |
| 70 | } |
| 71 | if (c === '"' || c === "'" || c === '`') { |
| 72 | const quote = c; |
| 73 | i++; |
| 74 | // An escape blanks both its characters, an escaped newline too; a |
| 75 | // template's own newlines stay. |
| 76 | let run = i; |
| 77 | while (i < n && text[i] !== quote) { |
| 78 | if (text[i] === '\\' && i + 1 < n) { |
| 79 | i += 2; |
| 80 | continue; |
| 81 | } |
| 82 | if (quote !== '`' && text[i] === '\n') break; |
| 83 | if (text[i] === '\n') { |
| 84 | blank(run, i); |
| 85 | run = i + 1; |
| 86 | } |
| 87 | i++; |
| 88 | } |
| 89 | blank(run, i); |
| 90 | if (i < n && text[i] === quote) i++; |
| 91 | continue; |
| 92 | } |
| 93 | i++; |
| 94 | } |
| 95 | if (copied === 0) return text; |
| 96 | parts.push(text.slice(copied)); |
| 97 | return parts.join(''); |
no test coverage detected