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

Method _replaceRegexp

src/MagicString.ts:1431–1503  ·  view source on GitHub ↗

@internal

(searchValue: RegExp, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1429
1430 /** @internal */
1431 _replaceRegexp(searchValue: RegExp, replacement: string | ReplacementFunction): this {
1432 function getReplacement(match: RegExpMatchArray, index: number, str: string): string {
1433 if (typeof replacement === 'string') {
1434 return expandReplacement(
1435 replacement,
1436 match[0],
1437 index,
1438 str,
1439 match.slice(1),
1440 match.groups,
1441 )
1442 }
1443 else {
1444 // `String.prototype.replace` only passes the named-capture-groups object
1445 // when the pattern actually has named groups - passing an `undefined`
1446 // there unconditionally shifts the last argument a replacer sees
1447 return match.groups === undefined
1448 ? replacement(match[0], ...match.slice(1), index, str)
1449 : replacement(match[0], ...match.slice(1), index, str, match.groups)
1450 }
1451 }
1452 // Returns true once a surviving match has been handled, so a non-global
1453 // search can stop at the first match still present in the output.
1454 const replaceMatch = (match: RegExpMatchArray): boolean => {
1455 /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
1456 if (match.index == null)
1457 return false
1458
1459 if (this._hasRemovedContent(match.index, match.index + match[0].length))
1460 return false
1461
1462 const replacement = getReplacement(match, match.index, this.original)
1463 if (replacement === match[0])
1464 return true
1465
1466 if (match[0].length === 0) {
1467 // a zero-length match spans no characters, so there is no range to
1468 // overwrite - the replacement is an insertion at the matched position,
1469 // which is what `String.prototype.replace` does for an empty match
1470 this.appendRight(match.index - this.offset, replacement)
1471 }
1472 else {
1473 this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement)
1474 }
1475 return true
1476 }
1477
1478 if (searchValue.global) {
1479 // `String.prototype.replace` starts a global regexp from the beginning of
1480 // the string, so reset `lastIndex` - a regexp that has already been used
1481 // would otherwise resume from wherever it stopped and skip earlier matches.
1482 // `matchAll` also steps over a zero-length match, where `exec` in a loop
1483 // would keep rematching it at an unmoving `lastIndex` and never terminate.
1484 searchValue.lastIndex = 0
1485 for (const match of this.original.matchAll(searchValue)) {
1486 replaceMatch(match)
1487 }
1488 }

Callers 2

replaceMethod · 0.95
replaceAllMethod · 0.95

Calls 1

matchAllMethod · 0.80

Tested by

no test coverage detected