Linter · Rules
@typescript-eslint/prefer-regexp-exec
Require pattern.exec(text) instead of text.match(pattern) when there is no g flag
The return value of text.match(pattern) depends on the flags of pattern. With g it's a list of all matches without their groups. Without g it's the first match with its groups, which is what pattern.exec(text) returns. If you use exec for one match and keep match for the g flag, the method name tells you which of the two you get.
A call is only reported if the rule can tell that there's no g flag. A regular expression that comes in as a parameter is left alone.
--fix rewrites the call. A string argument becomes a regular expression, so text.match("v1") becomes /v1/.exec(text).
Configure
Off by default. This rule needs types, so turning it on makes bun lint type check your code first.
[lint.rules]
"@typescript-eslint/prefer-regexp-exec" = "error" # or "warn"
Examples
Reported:
function version(text: string) {
return text.match(/v(\d+)/) ?? text.match("latest");
}
Not reported:
function version(text: string) {
return /v(\d+)/.exec(text) ?? /latest/.exec(text);
}
function numbers(text: string) {
return text.match(/\d+/g);
}
function search(text: string, pattern: RegExp) {
return text.match(pattern);
}