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

Method _replaceAllString

src/MagicString.ts:1301–1332  ·  view source on GitHub ↗

@internal

(string: string, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1299
1300 /** @internal */
1301 _replaceAllString(string: string, replacement: string | ReplacementFunction): this {
1302 const { original } = this
1303 const stringLength = string.length
1304
1305 // an empty search string matches the empty range before every character plus
1306 // one at the end, and `indexOf` clamps its start index to the string length,
1307 // so it can neither find those ranges nor ever report -1 - step through them
1308 if (stringLength === 0) {
1309 for (let index = 0; index <= original.length; index += 1) {
1310 const _replacement
1311 = typeof replacement === 'function' ? replacement('', index, original) : replacement
1312 if (_replacement !== '')
1313 this.appendRight(index, _replacement)
1314 }
1315
1316 return this
1317 }
1318
1319 for (
1320 let index = original.indexOf(string);
1321 index !== -1;
1322 index = original.indexOf(string, index + stringLength)
1323 ) {
1324 const previous = original.slice(index, index + stringLength)
1325 const _replacement
1326 = typeof replacement === 'function' ? replacement(previous, index, original) : replacement
1327 if (previous !== _replacement)
1328 this.overwrite(index, index + stringLength, _replacement)
1329 }
1330
1331 return this
1332 }
1333
1334 /**
1335 * Same as `s.replace`, but replace all matched strings instead of just one.

Callers 1

replaceAllMethod · 0.95

Calls 3

appendRightMethod · 0.95
overwriteMethod · 0.95
sliceMethod · 0.45

Tested by

no test coverage detected