Skip to content

unicorn/prefer-regexp-test Pedantic

🛠️ An auto-fix is available for this rule.

What it does

Prefers RegExp#test() over String#match() and String#exec().

Why is this bad?

When you want to know whether a pattern is found in a string, use RegExp#test() instead of String#match() and RegExp#exec(), as it exclusively returns a boolean and therefore is more efficient.

Example

Examples of incorrect code for this rule:

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

Examples of correct code for this rule:

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

How to use

To enable this rule in the CLI or using the config file, you can use:

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

References

Released under the MIT License.