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+")Use a regular expression literal instead of the RegExp constructor.;
const word = RegExp("hello", "gi")Use a regular expression literal instead of the RegExp constructor.;
const path = new RegExp(String.raw`\.tsx?$`)Use a regular expression literal instead of the RegExp constructor.;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#
| Option | Default | What it does |
|---|---|---|
disallowRedundantWrapping | false | Also report a regular expression literal passed to RegExp, alone or with fixed flags. |
example.jswith
{ "disallowRedundantWrapping": true }2 problemsconst digits = new RegExp(/\d+/)Regular expression literal is unnecessarily wrapped within a RegExp constructor.;
const word = new RegExp(/hello/, "gi")Use regular expression literal with flags instead of the RegExp constructor.;example.jswith
{ "disallowRedundantWrapping": true }No problemsconst digits = /\d+/;
const word = /hello/gi;
const custom = new RegExp(/hello/, flags);