prefer-regexp-exec
Enforce
RegExp#exec
overString#match
if no global flag is provided.
Extending "plugin:@typescript-eslint/stylistic-type-checked"
in an ESLint configuration enables this rule.
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
This rule requires type information to run.
String#match
is defined to work the same as RegExp#exec
when the regular expression does not include the g
flag.
Keeping to consistently using one of the two can help improve code readability.
This rule reports when a String#match
call can be replaced with an equivalent RegExp#exec
.
RegExp#exec
may also be slightly faster thanString#match
; this is the reason to choose it as the preferred usage.
module.exports = {
"rules": {
"@typescript-eslint/prefer-regexp-exec": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
'something'.match(/thing/);
'some things are just things'.match(/thing/);
const text = 'something';
const search = /thing/;
text.match(search);
Open in Playground/thing/.exec('something');
'some things are just things'.match(/thing/g);
const text = 'something';
const search = /thing/;
search.exec(text);
Open in PlaygroundOptions
This rule is not configurable.
When Not To Use It
If you prefer consistent use of String#match
for both with g
flag and without it, you can turn this rule off.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting. See Troubleshooting > Linting with Type Information > Performance if you experience performance degredations after enabling type checked rules.