Skip to content

Commit

Permalink
regex-shorthand - Escape backslash and apostrophe (#183)
Browse files Browse the repository at this point in the history
Fixes #178. While I was in there I realized that there was an implicit conversion between `"` and `'` which has another potential escaping issue.
  • Loading branch information
MrHen authored and sindresorhus committed Aug 23, 2018
1 parent 9f7f811 commit 8a50f40
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
12 changes: 11 additions & 1 deletion rules/regex-shorthand.js
Expand Up @@ -48,10 +48,20 @@ const create = context => {
const newPattern = cleanRegexp(oldPattern, flags);

if (oldPattern !== newPattern) {
let fixed;
if (hasRegExp) {
fixed = `/${newPattern}/`;
} else {
// Escape backslash and apostrophe because we wrap the result in single quotes.
fixed = (newPattern || '').replace(/\\/, '\\\\');
fixed = fixed.replace(/'/, '\'');
fixed = `'${fixed}'`;
}

context.report({
node,
message,
fix: fixer => fixer.replaceTextRange(args[0].range, hasRegExp ? `/${newPattern}/` : `'${newPattern}'`)
fix: fixer => fixer.replaceTextRange(args[0].range, fixed),
});
}
}
Expand Down
14 changes: 12 additions & 2 deletions test/regex-shorthand.js
Expand Up @@ -44,7 +44,17 @@ ruleTester.run('regex-shorthand', rule, {
{
code: `const foo = new RegExp('[0-9]')`,
errors: [error],
output: `const foo = new RegExp('\\d')`
output: `const foo = new RegExp('\\\\d')`
},
{
code: `const foo = new RegExp("[0-9]")`,
errors: [error],
output: `const foo = new RegExp('\\\\d')`
},
{
code: `const foo = new RegExp("'[0-9]'")`,
errors: [error],
output: `const foo = new RegExp('\'\\\\d\'')`
},
{
code: 'const foo = /[0-9]/ig',
Expand All @@ -54,7 +64,7 @@ ruleTester.run('regex-shorthand', rule, {
{
code: `const foo = new RegExp('[0-9]', 'ig')`,
errors: [error],
output: `const foo = new RegExp('\\d', 'ig')`
output: `const foo = new RegExp('\\\\d', 'ig')`
},
{
code: 'const foo = /[^0-9]/',
Expand Down

0 comments on commit 8a50f40

Please sign in to comment.