From 902541fdff3998e3c957908de10769d2af1a3c70 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Thu, 3 Mar 2022 17:06:32 +0800 Subject: [PATCH] fix(replace): match replacer function signature with spec --- src/MagicString.js | 8 ++++---- test/MagicString.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/MagicString.js b/src/MagicString.js index b67bf18..309a172 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -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 @@ -733,7 +733,7 @@ export default class MagicString { }); } else { - return replacement(...match); + return replacement(...match, match.index, str, match.groups); } } function matchAll(re, str) { @@ -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; } diff --git a/test/MagicString.js b/test/MagicString.js index 25472ff..57c1daf 100644 --- a/test/MagicString.js +++ b/test/MagicString.js @@ -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() + ); + }); }); });