Skip to content

Commit

Permalink
Update: add fixer for wrap-regex (fixes #7013) (#7048)
Browse files Browse the repository at this point in the history
  • Loading branch information
not-an-aardvark authored and btmills committed Sep 6, 2016
1 parent f4fcd1e commit e118728
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
2 changes: 2 additions & 0 deletions docs/rules/wrap-regex.md
@@ -1,5 +1,7 @@
# Require Regex Literals to be Wrapped (wrap-regex)

(fixable) The `--fix` option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.

When a regular expression is used in certain situations, it can end up looking like a division operator. For example:

```js
Expand Down
10 changes: 8 additions & 2 deletions lib/rules/wrap-regex.js
Expand Up @@ -17,7 +17,9 @@ module.exports = {
recommended: false
},

schema: []
schema: [],

fixable: "code"
},

create(context) {
Expand All @@ -36,7 +38,11 @@ module.exports = {

if (grandparent.type === "MemberExpression" && grandparent.object === node &&
(!source || source.value !== "(")) {
context.report(node, "Wrap the regexp literal in parens to disambiguate the slash.");
context.report({
node,
message: "Wrap the regexp literal in parens to disambiguate the slash.",
fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`)
});
}
}
}
Expand Down
15 changes: 10 additions & 5 deletions tests/lib/rules/wrap-regex.js
Expand Up @@ -28,10 +28,15 @@ ruleTester.run("wrap-regex", rule, {
"a[/b/];"
],
invalid: [
{ code: "/foo/.test(bar);",
errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}] },
{ code: "/foo/ig.test(bar);",
errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}] }

{
code: "/foo/.test(bar);",
errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}],
output: "(/foo/).test(bar);"
},
{
code: "/foo/ig.test(bar);",
errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}],
output: "(/foo/ig).test(bar);"
}
]
});

0 comments on commit e118728

Please sign in to comment.