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

Method _replaceString

src/MagicString.ts:1506–1539  ·  view source on GitHub ↗

@internal

(string: string, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

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