@internal
(searchValue: RegExp, replacement: string | ReplacementFunction)
| 1116 | |
| 1117 | /** @internal */ |
| 1118 | _replaceRegexp(searchValue: RegExp, replacement: string | ReplacementFunction): this { |
| 1119 | function getReplacement(match: RegExpMatchArray, str: string): string { |
| 1120 | if (typeof replacement === 'string') { |
| 1121 | return replacement.replace(/\$(\$|&|\d+)/g, (_: string, i: string) => { |
| 1122 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter |
| 1123 | if (i === '$') |
| 1124 | return '$' |
| 1125 | if (i === '&') |
| 1126 | return match[0] |
| 1127 | const num = +i |
| 1128 | if (num < match.length) |
| 1129 | return match[+i] |
| 1130 | return `$${i}` |
| 1131 | }) |
| 1132 | } |
| 1133 | else { |
| 1134 | return replacement(match[0], ...match.slice(1), match.index, str, match.groups) |
| 1135 | } |
| 1136 | } |
| 1137 | function matchAll(re: RegExp, str: string): RegExpExecArray[] { |
| 1138 | const matches = [] |
| 1139 | while (true) { |
| 1140 | const match = re.exec(str) |
| 1141 | if (!match) |
| 1142 | break |
| 1143 | |
| 1144 | matches.push(match) |
| 1145 | } |
| 1146 | return matches |
| 1147 | } |
| 1148 | if (searchValue.global) { |
| 1149 | const matches = matchAll(searchValue, this.original) |
| 1150 | matches.forEach((match) => { |
| 1151 | if (match.index != null) { |
| 1152 | const replacement = getReplacement(match, this.original) |
| 1153 | if (replacement !== match[0]) { |
| 1154 | this.overwrite(match.index, match.index + match[0].length, replacement) |
| 1155 | } |
| 1156 | } |
| 1157 | }) |
| 1158 | } |
| 1159 | else { |
| 1160 | const match = this.original.match(searchValue) |
| 1161 | if (match && match.index != null) { |
| 1162 | const replacement = getReplacement(match, this.original) |
| 1163 | if (replacement !== match[0]) { |
| 1164 | this.overwrite(match.index, match.index + match[0].length, replacement) |
| 1165 | } |
| 1166 | } |
| 1167 | } |
| 1168 | return this |
| 1169 | } |
| 1170 | |
| 1171 | /** @internal */ |
| 1172 | _replaceString(string: string, replacement: string | ReplacementFunction): this { |
no test coverage detected