Skip to content
← Back to rules

unicorn/prefer-regexp-test 严格

An auto-fix is available for this rule.

它的作用

优先使用 RegExp#test() 而非 String#match()String#exec()

为什么这是不好的?

当你需要判断某个模式是否在字符串中出现时,应使用 RegExp#test() 而非 String#match()RegExp#exec(), 因为它仅返回布尔值,因此效率更高。

示例

此规则的错误代码示例:

javascript
if (string.match(/unicorn/)) {
}
if (/unicorn/.exec(string)) {
}

此规则的正确代码示例:

javascript
if (/unicorn/.test(string)) {
}
Boolean(string.match(/unicorn/));

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "unicorn/prefer-regexp-test": "error"
  }
}
bash
oxlint --deny unicorn/prefer-regexp-test

参考资料