( text: string, regex: RegExp )
| 46 | * ] |
| 47 | */ |
| 48 | export function splitByRegex( |
| 49 | text: string, |
| 50 | regex: RegExp |
| 51 | ): Array<{index: number; matchesRegex: boolean; text: string}> { |
| 52 | // 'matchAll' requires a regex with the 'global' flag. |
| 53 | if (!regex.flags.includes('g')) { |
| 54 | regex = new RegExp(regex, regex.flags + 'g'); |
| 55 | } |
| 56 | |
| 57 | const result = []; |
| 58 | |
| 59 | // Index of the earliest unvisited character. |
| 60 | let lastIndex = 0; |
| 61 | for (const match of text.matchAll(regex)) { |
| 62 | const index = match.index as number; |
| 63 | const matchingText = match[0]; |
| 64 | |
| 65 | // Add any text between the last match and this current one. |
| 66 | if (index > lastIndex) { |
| 67 | result.push({ |
| 68 | index: lastIndex, |
| 69 | text: text.substring(lastIndex, index), |
| 70 | matchesRegex: false, |
| 71 | }); |
| 72 | } |
| 73 | |
| 74 | result.push({ |
| 75 | index, |
| 76 | text: matchingText, |
| 77 | matchesRegex: true, |
| 78 | }); |
| 79 | |
| 80 | lastIndex = index + matchingText.length; |
| 81 | } |
| 82 | |
| 83 | // Add the remaining text piece, if any. |
| 84 | if (text.length > lastIndex) { |
| 85 | result.push({ |
| 86 | index: lastIndex, |
| 87 | text: text.substring(lastIndex, text.length), |
| 88 | matchesRegex: false, |
| 89 | }); |
| 90 | } |
| 91 | |
| 92 | return result; |
| 93 | } |
| 94 | |
| 95 | // Based on |
| 96 | // https://cs.chromium.org/chromium/src/third_party/devtools-frontend/src/front_end/console/ConsoleViewMessage.js?q=linkstringregex |
no test coverage detected
searching dependent graphs…