prefer-regexp-exec
Enforce
RegExp#exec
overString#match
if no global flag is provided.
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
该规则需要 类型信息 才能运行。
当正则表达式不包含 g
标志时,String#match
被定义为与 RegExp#exec
相同的工作方式。
坚持使用两者之一有助于提高代码的可读性。
英: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.
此规则报告何时可以用等效的 RegExp#exec
替换 String#match
调用。
英:This rule reports when a String#match
call can be replaced with an equivalent RegExp#exec
.
RegExp#exec
也可能比String#match
稍快; 这就是选择它作为首选用途的原因。
module.exports = {
"rules": {
"@typescript-eslint/prefer-regexp-exec": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
'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 Playground何时不使用它
如果你希望在带有 g
标志和不带有 g
标志的情况下一致使用 String#match
,则可以关闭此规则。
英:If you prefer consistent use of String#match
for both with g
flag and without it, you can turn this rule off.
选项
该规则不可配置。