Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3be04fd

Browse files
mdjermanovicilyavolodin
authored andcommitted
New: Add prefer-regex-literals rule (fixes#12238) (#12254)
* New: Add prefer-regex-literals rule (fixes#12238)* Update docs/rules/prefer-regex-literals.mdCo-Authored-By: Kevin Partington <platinum.azure@kernelpanicstudios.com>* Update docs/rules/prefer-regex-literals.mdCo-Authored-By: Kevin Partington <platinum.azure@kernelpanicstudios.com>* Pass ecmaVersion to RuleTester constructor* Check global String reference
1 parent37c0fde commit3be04fd

File tree

5 files changed

+399
-0
lines changed

5 files changed

+399
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#Disallow use of the`RegExp` constructor in favor of regular expression literals (prefer-regex-literals)
2+
3+
There are two ways to create a regular expression:
4+
5+
* Regular expression literals, e.g.,`/abc/u`.
6+
* The`RegExp` constructor function, e.g.,`new RegExp("abc", "u")` or`RegExp("abc", "u")`.
7+
8+
The constructor function is particularly useful when you want to dynamically generate the pattern,
9+
because it takes string arguments.
10+
11+
When using the constructor function with string literals, don't forget that the string escaping rules still apply.
12+
If you want to put a backslash in the pattern, you need to escape it in the string literal.
13+
Thus, the following are equivalent:
14+
15+
```js
16+
newRegExp("^\\d\\.$");
17+
18+
/^\d\.$/;
19+
20+
// matches "0.", "1.", "2." ... "9."
21+
```
22+
23+
In the above example, the regular expression literal is easier to read and reason about.
24+
Also, it's a common mistake to omit the extra`\` in the string literal, which would produce a completely different regular expression:
25+
26+
```js
27+
newRegExp("^\d\.$");
28+
29+
// equivalent to /^d.$/, matches "d1", "d2", "da", "db" ...
30+
```
31+
32+
When a regular expression is known in advance, it is considered a best practice to avoid the string literal notation on top
33+
of the regular expression notation, and use regular expression literals instead of the constructor function.
34+
35+
##Rule Details
36+
37+
This rule disallows the use of the`RegExp` constructor function with string literals as its arguments.
38+
39+
This rule also disallows the use of the`RegExp` constructor function with template literals without expressions
40+
and`String.raw` tagged template literals without expressions.
41+
42+
The rule does not disallow all use of the`RegExp` constructor. It should be still used for
43+
dynamically generated regular expressions.
44+
45+
Examples of**incorrect** code for this rule:
46+
47+
```js
48+
newRegExp("abc");
49+
50+
newRegExp("abc","u");
51+
52+
RegExp("abc");
53+
54+
RegExp("abc","u");
55+
56+
newRegExp("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d");
57+
58+
RegExp(`^\\d\\.$`);
59+
60+
newRegExp(String.raw`^\d\.$`);
61+
```
62+
63+
Examples of**correct** code for this rule:
64+
65+
```js
66+
/abc/;
67+
68+
/abc/u;
69+
70+
/\d\d\.\d\d\.\d\d\d\d/;
71+
72+
/^\d\.$/;
73+
74+
// RegExp constructor is allowed for dynamically generated regular expressions
75+
76+
newRegExp(pattern);
77+
78+
RegExp("abc", flags);
79+
80+
newRegExp(prefix+"abc");
81+
82+
RegExp(`${prefix}abc`);
83+
84+
newRegExp(String.raw`^\d\.${sufix}`);
85+
```
86+
87+
##Further Reading
88+
89+
*[MDN: Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
90+
*[MDN: RegExp Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)

‎lib/rules/index.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
242242
"prefer-object-spread":()=>require("./prefer-object-spread"),
243243
"prefer-promise-reject-errors":()=>require("./prefer-promise-reject-errors"),
244244
"prefer-reflect":()=>require("./prefer-reflect"),
245+
"prefer-regex-literals":()=>require("./prefer-regex-literals"),
245246
"prefer-rest-params":()=>require("./prefer-rest-params"),
246247
"prefer-spread":()=>require("./prefer-spread"),
247248
"prefer-template":()=>require("./prefer-template"),

‎lib/rules/prefer-regex-literals.js‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/**
2+
*@fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals
3+
*@author Milos Djermanovic
4+
*/
5+
6+
"use strict";
7+
8+
//------------------------------------------------------------------------------
9+
// Requirements
10+
//------------------------------------------------------------------------------
11+
12+
constastUtils=require("./utils/ast-utils");
13+
const{CALL,CONSTRUCT, ReferenceTracker, findVariable}=require("eslint-utils");
14+
15+
//------------------------------------------------------------------------------
16+
// Helpers
17+
//------------------------------------------------------------------------------
18+
19+
/**
20+
* Determines whether the given node is a string literal.
21+
*@param {ASTNode} node Node to check.
22+
*@returns {boolean} True if the node is a string literal.
23+
*/
24+
functionisStringLiteral(node){
25+
returnnode.type==="Literal"&&typeofnode.value==="string";
26+
}
27+
28+
/**
29+
* Determines whether the given node is a template literal without expressions.
30+
*@param {ASTNode} node Node to check.
31+
*@returns {boolean} True if the node is a template literal without expressions.
32+
*/
33+
functionisStaticTemplateLiteral(node){
34+
returnnode.type==="TemplateLiteral"&&node.expressions.length===0;
35+
}
36+
37+
38+
//------------------------------------------------------------------------------
39+
// Rule Definition
40+
//------------------------------------------------------------------------------
41+
42+
module.exports={
43+
meta:{
44+
type:"suggestion",
45+
46+
docs:{
47+
description:"disallow use of the `RegExp` constructor in favor of regular expression literals",
48+
category:"Best Practices",
49+
recommended:false,
50+
url:"https://eslint.org/docs/rules/prefer-regex-literals"
51+
},
52+
53+
schema:[],
54+
55+
messages:{
56+
unexpectedRegExp:"Use a regular expression literal instead of the 'RegExp' constructor."
57+
}
58+
},
59+
60+
create(context){
61+
62+
/**
63+
* Determines whether the given identifier node is a reference to a global variable.
64+
*@param {ASTNode} node `Identifier` node to check.
65+
*@returns {boolean} True if the identifier is a reference to a global variable.
66+
*/
67+
functionisGlobalReference(node){
68+
constscope=context.getScope();
69+
constvariable=findVariable(scope,node);
70+
71+
returnvariable!==null&&variable.scope.type==="global"&&variable.defs.length===0;
72+
}
73+
74+
/**
75+
* Determines whether the given node is a String.raw`` tagged template expression
76+
* with a static template literal.
77+
*@param {ASTNode} node Node to check.
78+
*@returns {boolean} True if the node is String.raw`` with a static template.
79+
*/
80+
functionisStringRawTaggedStaticTemplateLiteral(node){
81+
returnnode.type==="TaggedTemplateExpression"&&
82+
node.tag.type==="MemberExpression"&&
83+
node.tag.object.type==="Identifier"&&
84+
node.tag.object.name==="String"&&
85+
isGlobalReference(node.tag.object)&&
86+
astUtils.getStaticPropertyName(node.tag)==="raw"&&
87+
isStaticTemplateLiteral(node.quasi);
88+
}
89+
90+
/**
91+
* Determines whether the given node is considered to be a static string by the logic of this rule.
92+
*@param {ASTNode} node Node to check.
93+
*@returns {boolean} True if the node is a static string.
94+
*/
95+
functionisStaticString(node){
96+
returnisStringLiteral(node)||
97+
isStaticTemplateLiteral(node)||
98+
isStringRawTaggedStaticTemplateLiteral(node);
99+
}
100+
101+
return{
102+
Program(){
103+
constscope=context.getScope();
104+
consttracker=newReferenceTracker(scope);
105+
consttraceMap={
106+
RegExp:{
107+
[CALL]:true,
108+
[CONSTRUCT]:true
109+
}
110+
};
111+
112+
for(const{ node}oftracker.iterateGlobalReferences(traceMap)){
113+
constargs=node.arguments;
114+
115+
if(
116+
(args.length===1||args.length===2)&&
117+
args.every(isStaticString)
118+
){
119+
context.report({ node,messageId:"unexpectedRegExp"});
120+
}
121+
}
122+
}
123+
};
124+
}
125+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp