Skip to content

useRegexLiterals (since v1.3.0)

Diagnostic Category: lint/complexity/useRegexLiterals

Sources:

Enforce 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.

new RegExp("abc", "u");
complexity/useRegexLiterals.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  
  
/abc/u;
new RegExp("abc", flags);