Skip to content

Commit 88595be

Browse files
ritazoliveirasindresorhus
authored andcommitted
Respect newlines and tabs in replacement string (#3)
1 parent 6f8afd1 commit 88595be

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

api.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ module.exports = async (filePaths, {find, replacement, ignoreCase} = {}) => {
2626
throw new Error('The `replacement` option is required');
2727
}
2828

29+
// Replace the replacement string with the string unescaped (only one backslash) if it's escaped
30+
replacement = replacement
31+
.replace(/\\n/g, '\n')
32+
.replace(/\\r/g, '\r')
33+
.replace(/\\t/g, '\t');
34+
2935
// Deduplicate
3036
filePaths = [...new Set(filePaths.map(filePath => path.resolve(filePath)))];
3137

test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,23 @@ test('--regex', async t => {
1414
await execa('./cli.js', ['--regex=\\bb.*?\\b', '--replacement=foo', filePath]);
1515
t.is(fs.readFileSync(filePath, 'utf8'), 'foo foo foo');
1616
});
17+
18+
test('newlines and tabs', async t => {
19+
const filePath = await tempWrite('a,b,c');
20+
await execa('./cli.js', ['--string=,', '--replacement=\\n', filePath]);
21+
t.is(fs.readFileSync(filePath, 'utf8'), 'a\nb\nc');
22+
23+
const filePath2 = await tempWrite('a,b,c');
24+
await execa('./cli.js', ['--string=,', '--replacement=\\t', filePath2]);
25+
t.is(fs.readFileSync(filePath2, 'utf8'), 'a\tb\tc');
26+
27+
const filePath3 = await tempWrite('a,b,c');
28+
await execa('./cli.js', ['--string=,', '--replacement=\\r', filePath3]);
29+
t.is(fs.readFileSync(filePath3, 'utf8'), 'a\rb\rc');
30+
});
31+
32+
test('multiple newlines and tabs', async t => {
33+
const filePath = await tempWrite('a,b,c');
34+
await execa('./cli.js', ['--string=,', '--replacement=\\n\\n\\t\\r', filePath]);
35+
t.is(fs.readFileSync(filePath, 'utf8'), 'a\n\n\t\rb\n\n\t\rc');
36+
});

0 commit comments

Comments
 (0)