Skip to content

Commit 8a50f40

Browse files
MrHensindresorhus
authored andcommitted
regex-shorthand - Escape backslash and apostrophe (#183)
Fixes #178. While I was in there I realized that there was an implicit conversion between `"` and `'` which has another potential escaping issue.
1 parent 9f7f811 commit 8a50f40

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

rules/regex-shorthand.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,20 @@ const create = context => {
4848
const newPattern = cleanRegexp(oldPattern, flags);
4949

5050
if (oldPattern !== newPattern) {
51+
let fixed;
52+
if (hasRegExp) {
53+
fixed = `/${newPattern}/`;
54+
} else {
55+
// Escape backslash and apostrophe because we wrap the result in single quotes.
56+
fixed = (newPattern || '').replace(/\\/, '\\\\');
57+
fixed = fixed.replace(/'/, '\'');
58+
fixed = `'${fixed}'`;
59+
}
60+
5161
context.report({
5262
node,
5363
message,
54-
fix: fixer => fixer.replaceTextRange(args[0].range, hasRegExp ? `/${newPattern}/` : `'${newPattern}'`)
64+
fix: fixer => fixer.replaceTextRange(args[0].range, fixed),
5565
});
5666
}
5767
}

test/regex-shorthand.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,17 @@ ruleTester.run('regex-shorthand', rule, {
4444
{
4545
code: `const foo = new RegExp('[0-9]')`,
4646
errors: [error],
47-
output: `const foo = new RegExp('\\d')`
47+
output: `const foo = new RegExp('\\\\d')`
48+
},
49+
{
50+
code: `const foo = new RegExp("[0-9]")`,
51+
errors: [error],
52+
output: `const foo = new RegExp('\\\\d')`
53+
},
54+
{
55+
code: `const foo = new RegExp("'[0-9]'")`,
56+
errors: [error],
57+
output: `const foo = new RegExp('\'\\\\d\'')`
4858
},
4959
{
5060
code: 'const foo = /[0-9]/ig',
@@ -54,7 +64,7 @@ ruleTester.run('regex-shorthand', rule, {
5464
{
5565
code: `const foo = new RegExp('[0-9]', 'ig')`,
5666
errors: [error],
57-
output: `const foo = new RegExp('\\d', 'ig')`
67+
output: `const foo = new RegExp('\\\\d', 'ig')`
5868
},
5969
{
6070
code: 'const foo = /[^0-9]/',

0 commit comments

Comments
 (0)