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

Method _replaceAllString

src/MagicString.ts:1438–1473  ·  view source on GitHub ↗

@internal

(string: string, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1436
1437 /** @internal */
1438 _replaceAllString(string: string, replacement: string | ReplacementFunction): this {
1439 const { original } = this
1440 const stringLength = string.length
1441
1442 // an empty search string matches the empty range before every character plus
1443 // one at the end, and `indexOf` clamps its start index to the string length,
1444 // so it can neither find those ranges nor ever report -1 - step through them
1445 if (stringLength === 0) {
1446 for (let index = 0; index <= original.length; index += 1) {
1447 const _replacement
1448 = typeof replacement === 'function'
1449 ? replacement('', index, original)
1450 : expandReplacement(replacement, '', index, original, [], undefined)
1451 if (_replacement !== '')
1452 this.appendRight(index, _replacement)
1453 }
1454
1455 return this
1456 }
1457
1458 for (
1459 let index = original.indexOf(string);
1460 index !== -1;
1461 index = original.indexOf(string, index + stringLength)
1462 ) {
1463 const previous = original.slice(index, index + stringLength)
1464 const _replacement
1465 = typeof replacement === 'function'
1466 ? replacement(previous, index, original)
1467 : expandReplacement(replacement, previous, index, original, [], undefined)
1468 if (previous !== _replacement)
1469 this.overwrite(index, index + stringLength, _replacement)
1470 }
1471
1472 return this
1473 }
1474
1475 /**
1476 * Same as `s.replace`, but replace all matched strings instead of just one.

Callers 1

replaceAllMethod · 0.95

Calls 4

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

Tested by

no test coverage detected