MCPcopy Create free account
hub / github.com/Rich-Harris/magic-string / _replaceRegexp

Method _replaceRegexp

src/MagicString.ts:1198–1249  ·  view source on GitHub ↗

@internal

(searchValue: RegExp, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1196
1197 /** @internal */
1198 _replaceRegexp(searchValue: RegExp, replacement: string | ReplacementFunction): this {
1199 function getReplacement(match: RegExpMatchArray, str: string): string {
1200 if (typeof replacement === 'string') {
1201 return replacement.replace(/\$(\$|&|\d+)/g, (_: string, i: string) => {
1202 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1203 if (i === '$')
1204 return '$'
1205 if (i === '&')
1206 return match[0]
1207 const num = +i
1208 if (num < match.length)
1209 return match[+i]
1210 return `$${i}`
1211 })
1212 }
1213 else {
1214 return replacement(match[0], ...match.slice(1), match.index, str, match.groups)
1215 }
1216 }
1217 function matchAll(re: RegExp, str: string): RegExpExecArray[] {
1218 const matches = []
1219 while (true) {
1220 const match = re.exec(str)
1221 if (!match)
1222 break
1223
1224 matches.push(match)
1225 }
1226 return matches
1227 }
1228 if (searchValue.global) {
1229 const matches = matchAll(searchValue, this.original)
1230 matches.forEach((match) => {
1231 if (match.index != null) {
1232 const replacement = getReplacement(match, this.original)
1233 if (replacement !== match[0]) {
1234 this.overwrite(match.index, match.index + match[0].length, replacement)
1235 }
1236 }
1237 })
1238 }
1239 else {
1240 const match = this.original.match(searchValue)
1241 if (match && match.index != null) {
1242 const replacement = getReplacement(match, this.original)
1243 if (replacement !== match[0]) {
1244 this.overwrite(match.index, match.index + match[0].length, replacement)
1245 }
1246 }
1247 }
1248 return this
1249 }
1250
1251 /** @internal */
1252 _replaceString(string: string, replacement: string | ReplacementFunction): this {

Callers 2

replaceMethod · 0.95
replaceAllMethod · 0.95

Calls 1

overwriteMethod · 0.95

Tested by

no test coverage detected