Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/MagicString.js
Original file line number Diff line number Diff line change
Expand Up @@ -860,7 +860,12 @@ export default class MagicString {
const index = original.indexOf(string);

if (index !== -1) {
this.overwrite(index, index + string.length, replacement);
if (typeof replacement === 'function') {
replacement = replacement(string);
}
if (string !== replacement) {
this.overwrite(index, index + string.length, replacement);
}
}

return this;
Expand All @@ -883,6 +888,9 @@ export default class MagicString {
index = original.indexOf(string, index + stringLength)
) {
const previous = original.slice(index, index + stringLength);
if (typeof replacement === 'function') {
replacement = replacement(previous);
}
if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
}

Expand Down
17 changes: 17 additions & 0 deletions test/MagicString.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1804,6 +1804,15 @@ describe('MagicString', () => {
assert.strictEqual(s.toString(), '1 3 1 2');
});

it('works with string replace and function replacer', () => {
const code = '1 2 1 2';
const s = new MagicString(code);

s.replace('2', (match) => match + '-3');

assert.strictEqual(s.toString(), '1 2-3 1 2');
});

it('Should not treat string as regexp', () => {
assert.strictEqual(new MagicString('1234').replace('.', '*').toString(), '1234');
});
Expand Down Expand Up @@ -1879,6 +1888,14 @@ describe('MagicString', () => {
it('works with string replace', () => {
assert.strictEqual(new MagicString('1212').replaceAll('2', '3').toString(), '1313');
});
it('works with string replace and function replacer', () => {
const code = '1 2 1 2';
const s = new MagicString(code);

s.replaceAll('2', (match) => match + '-3');

assert.strictEqual(s.toString(), '1 2-3 1 2-3');
});

it('Should not treat string as regexp', () => {
assert.strictEqual(new MagicString('1234').replaceAll('.', '*').toString(), '1234');
Expand Down
Loading