no-invalid-regexp
Disallow invalid patterns and flags in RegExp() and new RegExp()
error by default
A mistake in a regular expression literal is a syntax error, so you see it right away. A pattern passed to RegExp as a string is only checked when that line runs, and then it throws a SyntaxError. This rule checks the string ahead of time.
Only string literals are checked. If the pattern or the flags come from a variable, that part is skipped.
This rule is on by default.
Configure#
On by default as an error. To turn it off:
bunfig.toml
[lint.rules]
"no-invalid-regexp" = "off" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"no-invalid-regexp" = ["error", {
allowConstructorFlags = [], # list of strings
}]Examples#
example.js4 problems
const letters = new RegExp("[a-z")Invalid regular expression: /[a-z/: Unterminated character class.;
const digits = RegExp("(\\d+")Invalid regular expression: /(\d+/: Unterminated group.;
const twice = new RegExp("\\d+", "gg")Duplicate flags (g) supplied to RegExp constructor.;
const unknown = new RegExp("\\d+", "x")Invalid flags supplied to RegExp constructor x.;example.jsNo problems
const letters = new RegExp("[a-z]");
const digits = RegExp("(\\d+)", "g");
const search = new RegExp(pattern, flags);Options#
| Option | Default | What it does |
|---|---|---|
allowConstructorFlags | [] | Extra flags to accept, one letter each, for a runtime that supports flags the standard doesn't have. Case matters. |
example.jswith
{ "allowConstructorFlags": ["x"] }No problemsconst digits = new RegExp("\\d+", "x");example.jswith
{ "allowConstructorFlags": ["x"] }1 problemconst digits = new RegExp("\\d+", "X")Invalid flags supplied to RegExp constructor X.;