UNPKG

1.67 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag when regex literals are not wrapped in parens
3 * @author Matt DuVall <http://www.mattduvall.com>
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 docs: {
15 description: "require parenthesis around regex literals",
16 category: "Stylistic Issues",
17 recommended: false,
18 url: "https://eslint.org/docs/rules/wrap-regex"
19 },
20
21 schema: [],
22
23 fixable: "code"
24 },
25
26 create(context) {
27 const sourceCode = context.getSourceCode();
28
29 return {
30
31 Literal(node) {
32 const token = sourceCode.getFirstToken(node),
33 nodeType = token.type;
34
35 if (nodeType === "RegularExpression") {
36 const source = sourceCode.getTokenBefore(node);
37 const ancestors = context.getAncestors();
38 const grandparent = ancestors[ancestors.length - 1];
39
40 if (grandparent.type === "MemberExpression" && grandparent.object === node &&
41 (!source || source.value !== "(")) {
42 context.report({
43 node,
44 message: "Wrap the regexp literal in parens to disambiguate the slash.",
45 fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`)
46 });
47 }
48 }
49 }
50 };
51
52 }
53};