Skip to content

Commit

Permalink
fix(replace): match replacer function signature with spec
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Mar 3, 2022
1 parent 877b834 commit 902541f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/MagicString.js
Expand Up @@ -718,7 +718,7 @@ export default class MagicString {
}

replace(searchValue, replacement) {
function getReplacement(match) {
function getReplacement(match, str) {
if (typeof replacement === 'string') {
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
Expand All @@ -733,7 +733,7 @@ export default class MagicString {
});
}
else {
return replacement(...match);
return replacement(...match, match.index, str, match.groups);
}
}
function matchAll(re, str) {
Expand All @@ -748,13 +748,13 @@ export default class MagicString {
const matches = matchAll(searchValue, this.original);
matches.forEach((match) => {
if (match.index != null)
this.overwrite(match.index, match.index + match[0].length, getReplacement(match));
this.overwrite(match.index, match.index + match[0].length, getReplacement(match, this.original));
});
}
else {
const match = this.original.match(searchValue);
if (match && match.index != null)
this.overwrite(match.index, match.index + match[0].length, getReplacement(match));
this.overwrite(match.index, match.index + match[0].length, getReplacement(match, this.original));
}
return this;
}
Expand Down
14 changes: 14 additions & 0 deletions test/MagicString.js
Expand Up @@ -1332,5 +1332,19 @@ describe('MagicString', () => {

assert.strictEqual(s.toString(),'Hey This Is Magic');
});

it('replace function offset', () => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_a_parameter
function replacer(match, p1, p2, p3, offset, string, groups) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [match, p1, p2, p3, offset, string, groups].join(' - ');
}
const code = 'abc12345#$*%';
const regex = /([^\d]*)(\d*)([^\w]*)/;
assert.strictEqual(
code.replace(regex, replacer),
new MagicString(code).replace(regex, replacer).toString()
);
});
});
});

0 comments on commit 902541f

Please sign in to comment.