prefer-regex-literals

Require regular expression literals instead of RegExp() with a fixed pattern

has suggestions

In new RegExp("\\d+") you write every backslash twice. Forget one and the pattern changes without an error, because "\d+" is the string d+. In the literal /\d+/ you write the pattern as is, and a mistake in it is a syntax error, not an exception when that line runs.

A call is reported if the pattern and the flags are fixed strings: a string literal, a template literal without ${}, or String.raw without ${}. A pattern that's built at run time needs the constructor, so it isn't reported.

The report comes with a suggestion that replaces the call with the literal.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"prefer-regex-literals" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"prefer-regex-literals" = ["error", {
  disallowRedundantWrapping = false,
}]

Examples#

example.js3 problems
const digits = new RegExp("\\d+");
const word = RegExp("hello", "gi");
const path = new RegExp(String.raw`\.tsx?$`);
example.jsNo problems
const digits = /\d+/;
const word = /hello/gi;
const path = /\.tsx?$/;

const search = new RegExp(escape(query), "i");
const prefix = new RegExp(`^${name}:`);

Options#

OptionDefaultWhat it does
disallowRedundantWrappingfalseAlso report a regular expression literal passed to RegExp, alone or with fixed flags.
example.jswith { "disallowRedundantWrapping": true }2 problems
const digits = new RegExp(/\d+/);
const word = new RegExp(/hello/, "gi");
example.jswith { "disallowRedundantWrapping": true }No problems
const digits = /\d+/;
const word = /hello/gi;
const custom = new RegExp(/hello/, flags);