Skip to content

Commit 902541f

Browse files
committedMar 3, 2022
fix(replace): match replacer function signature with spec
1 parent 877b834 commit 902541f

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed
 

‎src/MagicString.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,7 @@ export default class MagicString {
718718
}
719719

720720
replace(searchValue, replacement) {
721-
function getReplacement(match) {
721+
function getReplacement(match, str) {
722722
if (typeof replacement === 'string') {
723723
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
724724
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
@@ -733,7 +733,7 @@ export default class MagicString {
733733
});
734734
}
735735
else {
736-
return replacement(...match);
736+
return replacement(...match, match.index, str, match.groups);
737737
}
738738
}
739739
function matchAll(re, str) {
@@ -748,13 +748,13 @@ export default class MagicString {
748748
const matches = matchAll(searchValue, this.original);
749749
matches.forEach((match) => {
750750
if (match.index != null)
751-
this.overwrite(match.index, match.index + match[0].length, getReplacement(match));
751+
this.overwrite(match.index, match.index + match[0].length, getReplacement(match, this.original));
752752
});
753753
}
754754
else {
755755
const match = this.original.match(searchValue);
756756
if (match && match.index != null)
757-
this.overwrite(match.index, match.index + match[0].length, getReplacement(match));
757+
this.overwrite(match.index, match.index + match[0].length, getReplacement(match, this.original));
758758
}
759759
return this;
760760
}

‎test/MagicString.js

+14
Original file line numberDiff line numberDiff line change
@@ -1332,5 +1332,19 @@ describe('MagicString', () => {
13321332

13331333
assert.strictEqual(s.toString(),'Hey This Is Magic');
13341334
});
1335+
1336+
it('replace function offset', () => {
1337+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_a_parameter
1338+
function replacer(match, p1, p2, p3, offset, string, groups) {
1339+
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
1340+
return [match, p1, p2, p3, offset, string, groups].join(' - ');
1341+
}
1342+
const code = 'abc12345#$*%';
1343+
const regex = /([^\d]*)(\d*)([^\w]*)/;
1344+
assert.strictEqual(
1345+
code.replace(regex, replacer),
1346+
new MagicString(code).replace(regex, replacer).toString()
1347+
);
1348+
});
13351349
});
13361350
});

0 commit comments

Comments
 (0)
Please sign in to comment.