Skip to content

useRegexLiterals

诊断类别:lint/complexity/useRegexLiterals

¥Diagnostic Category: lint/complexity/useRegexLiterals

自从:v1.3.0

¥Since: v1.3.0

来源:

¥Sources:

如果可能,强制使用正则表达式文字而不是 RegExp 构造函数。

¥Enforce the use of the regular expression literals instead of the RegExp constructor if possible.

有两种创建正则表达式的方法:

¥There are two ways to create a regular expression:

  • 正则表达式文字,例如 /abc/u

    ¥Regular expression literals, e.g., /abc/u.

  • RegExp 构造函数,例如 new RegExp("abc", "u")

    ¥The RegExp constructor function, e.g., new RegExp("abc", "u") .

当你想要动态生成模式时,构造函数特别有用,因为它需要字符串参数。

¥The constructor function is particularly useful when you want to dynamically generate the pattern, because it takes string arguments.

使用正则表达式文字可以避免字符串文字中所需的一些转义,并且更容易进行静态分析。

¥Using regular expression literals avoids some escaping required in a string literal, and are easier to analyze statically.

¥Examples

¥Invalid

new RegExp("abc", "u");
code-block.js:1:1 lint/complexity/useRegexLiterals  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Use a regular expression literal instead of the RegExp constructor.

> 1 │ new RegExp(“abc”, “u”);
^^^^^^^^^^^^^^^^^^^^^^
2 │

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.

Safe fix: Use a literal notation instead.

1 - new·RegExp(abc,·u);
1+ /abc/u;
2 2

¥Valid

/abc/u;
new RegExp("abc", flags);

¥Related links