Skip to content

fix: don't resurrect removed content in replace/replaceAll - #352

Merged
antfu merged 2 commits into
Rich-Harris:masterfrom
antfubot:fix/replace-removed-code
Sep 15, 2026
Merged

antfu merged 2 commits into
Rich-Harris:masterfrom
antfubot:fix/replace-removed-code

Conversation

@antfubot

Copy link
Copy Markdown
Contributor

Problem

Fixes #223. replace/replaceAll search the original string by index and then overwrite the matched range. When those characters had already been removed, overwriting them brought the removed content back:

new MagicString('00').remove(0, 1).replace('0', '1').toString()
// '10'  ->  expected '1'

Fix

A match whose original characters have been removed no longer exists in the output, so it should not be edited. replace/replaceAll now skip matches landing on removed content and, for the single-match variants, advance to the first match still present in the output. The non-global regexp path keeps using String.prototype.match (so a custom Symbol.match is still honoured) and only scans forward when the first match turns out to be removed.

new MagicString('00').remove(0, 1).replace('0', '1').toString()      // '1'
new MagicString('000').remove(0, 1).replaceAll('0', '1').toString()  // '11'

This PR was created with the help of an agent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.replace replacing removed code

2 participants