跳到內容

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/));

參考資料

以 MIT 許可證發布。