Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update: add fixer for wrap-regex (fixes #7013) #7048

Merged
merged 1 commit into from
Sep 6, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/rules/wrap-regex.md
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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);"
}
]
});