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

Method _replaceAllString

src/MagicString.ts:1572–1615  ·  view source on GitHub ↗

@internal

(string: string, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1570
1571 /** @internal */
1572 _replaceAllString(string: string, replacement: string | ReplacementFunction): this {
1573 const { original } = this
1574 const stringLength = string.length
1575
1576 // an empty search string matches the empty range before every character plus
1577 // one at the end, and `indexOf` clamps its start index to the string length,
1578 // so it can neither find those ranges nor ever report -1 - step through them
1579 if (stringLength === 0) {
1580 for (let index = 0; index <= original.length; index += 1) {
1581 // an empty match inside removed content is not in the output, so skip it
1582 // and leave the replacer uncalled, as the regexp path does
1583 if (this._hasRemovedContent(index, index))
1584 continue
1585
1586 const _replacement
1587 = typeof replacement === 'function'
1588 ? replacement('', index, original)
1589 : expandReplacement(replacement, '', index, original, [], undefined)
1590 if (_replacement !== '')
1591 this.appendRight(index, _replacement)
1592 }
1593
1594 return this
1595 }
1596
1597 for (
1598 let index = original.indexOf(string);
1599 index !== -1;
1600 index = original.indexOf(string, index + stringLength)
1601 ) {
1602 if (this._hasRemovedContent(index, index + stringLength))
1603 continue
1604
1605 const previous = original.slice(index, index + stringLength)
1606 const _replacement
1607 = typeof replacement === 'function'
1608 ? replacement(previous, index, original)
1609 : expandReplacement(replacement, previous, index, original, [], undefined)
1610 if (previous !== _replacement)
1611 this.overwrite(index, index + stringLength, _replacement)
1612 }
1613
1614 return this
1615 }
1616
1617 /**
1618 * Same as `s.replace`, but replace all matched strings instead of just one.

Callers 1

replaceAllMethod · 0.95

Calls 5

_hasRemovedContentMethod · 0.95
appendRightMethod · 0.95
overwriteMethod · 0.95
expandReplacementFunction · 0.85
sliceMethod · 0.45

Tested by

no test coverage detected