prefer-regexp-exec
Enforce
RegExp#exec
overString#match
if no global flag is provided.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic-type-checked"
可启用此规则。
此规则报告的一些问题可通过 --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.
此规则报告何时 String#match
操作组合了两个不同类型的值,或不是 RegExp#exec
、 或 的类型。
¥This rule reports when a String#match
call can be replaced with an equivalent RegExp#exec
.
RegExp#exec
也可能比String#match
稍快;这就是选择它作为首选用途的原因。¥
RegExp#exec
may also be slightly faster thanString#match
; this is the reason to choose it as the preferred usage.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-regexp-exec": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/prefer-regexp-exec": "error"
}
};
在线运行试试这个规则 ↗
示例
¥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 Playground选项
该规则不可配置。