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

Method _replaceString

src/MagicString.ts:1511–1544  ·  view source on GitHub ↗

@internal

(string: string, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1509
1510 /** @internal */
1511 _replaceString(string: string, replacement: string | ReplacementFunction): this {
1512 const { original } = this
1513
1514 // skip occurrences whose characters have been removed, so the first match
1515 // still present in the output is the one replaced
1516 let index = original.indexOf(string)
1517 while (index !== -1) {
1518 if (this._hasRemovedContent(index, index + string.length)) {
1519 index = original.indexOf(string, index + string.length)
1520 continue
1521 }
1522
1523 if (typeof replacement === 'function') {
1524 replacement = replacement(string, index, original)
1525 }
1526 else {
1527 replacement = expandReplacement(replacement, string, index, original, [], undefined)
1528 }
1529 if (string !== replacement) {
1530 if (string.length === 0) {
1531 // an empty search string matches the empty range at the start of the
1532 // string, which has no characters to overwrite - the replacement is an
1533 // insertion there, as it is for `String.prototype.replace`
1534 this.appendRight(index, replacement)
1535 }
1536 else {
1537 this.overwrite(index, index + string.length, replacement)
1538 }
1539 }
1540 break
1541 }
1542
1543 return this
1544 }
1545
1546 /**
1547 * String replacement with RegExp or string.

Callers 1

replaceMethod · 0.95

Calls 4

_hasRemovedContentMethod · 0.95
appendRightMethod · 0.95
overwriteMethod · 0.95
expandReplacementFunction · 0.85

Tested by

no test coverage detected