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