unicorn/prefer-regexp-test 严格
它的作用
优先使用 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