useRegexLiterals
Diagnostic Category: lint/complexity/useRegexLiterals
Since: v1.3.0
Sources:
- Same as:
prefer-regex-literals
Description
Section titled DescriptionEnforce the use of the regular expression literals instead of the RegExp constructor if possible.
There are two ways to create a regular expression:
- Regular expression literals, e.g.,
/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
Section titled ExamplesInvalid
Section titled Invalidnew 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
Section titled Valid/abc/u;
new RegExp("abc", flags);How to configure
Section titled How to configure{ "linter": { "rules": { "complexity": { "useRegexLiterals": "error" } } }}