unicorn/prefer-regexp-test Pedantic
它的作用
优先使用 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/));如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"unicorn/prefer-regexp-test": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/prefer-regexp-test": "error",
},
});bash
oxlint --deny unicorn/prefer-regexp-test版本
此规则是在 v0.0.16 中添加的。
