@internal
(searchValue: RegExp, replacement: string | ReplacementFunction)
| 1158 | |
| 1159 | /** @internal */ |
| 1160 | _replaceRegexp(searchValue: RegExp, replacement: string | ReplacementFunction): this { |
| 1161 | function getReplacement(match: RegExpMatchArray, str: string): string { |
| 1162 | if (typeof replacement === 'string') { |
| 1163 | return replacement.replace(/\$(\$|&|\d+)/g, (_: string, i: string) => { |
| 1164 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter |
| 1165 | if (i === '$') |
| 1166 | return '$' |
| 1167 | if (i === '&') |
| 1168 | return match[0] |
| 1169 | const num = +i |
| 1170 | if (num < match.length) |
| 1171 | return match[+i] |
| 1172 | return `$${i}` |
| 1173 | }) |
| 1174 | } |
| 1175 | else { |
| 1176 | return replacement(match[0], ...match.slice(1), match.index, str, match.groups) |
| 1177 | } |
| 1178 | } |
| 1179 | function matchAll(re: RegExp, str: string): RegExpExecArray[] { |
| 1180 | const matches = [] |
| 1181 | while (true) { |
| 1182 | const match = re.exec(str) |
| 1183 | if (!match) |
| 1184 | break |
| 1185 | |
| 1186 | matches.push(match) |
| 1187 | } |
| 1188 | return matches |
| 1189 | } |
| 1190 | if (searchValue.global) { |
| 1191 | const matches = matchAll(searchValue, this.original) |
| 1192 | matches.forEach((match) => { |
| 1193 | if (match.index != null) { |
| 1194 | const replacement = getReplacement(match, this.original) |
| 1195 | if (replacement !== match[0]) { |
| 1196 | this.overwrite(match.index, match.index + match[0].length, replacement) |
| 1197 | } |
| 1198 | } |
| 1199 | }) |
| 1200 | } |
| 1201 | else { |
| 1202 | const match = this.original.match(searchValue) |
| 1203 | if (match && match.index != null) { |
| 1204 | const replacement = getReplacement(match, this.original) |
| 1205 | if (replacement !== match[0]) { |
| 1206 | this.overwrite(match.index, match.index + match[0].length, replacement) |
| 1207 | } |
| 1208 | } |
| 1209 | } |
| 1210 | return this |
| 1211 | } |
| 1212 | |
| 1213 | /** @internal */ |
| 1214 | _replaceString(string: string, replacement: string | ReplacementFunction): this { |
no test coverage detected