This rule raises an issue when String.match() or RegExp.exec() methods are used in boolean contexts where only the existence of a match matters, not the actual match details.

Why is this an issue?

When you only need to check if a regular expression pattern exists in a string, using String.match() or RegExp.exec() is inefficient. These methods create and return match objects or arrays containing detailed information about the matches, which requires additional memory allocation and processing time.

The RegExp.test() method is specifically designed for boolean checks. It returns true if the pattern is found and false otherwise, without creating any match objects. This makes it faster and more memory-efficient for simple existence checks.

Using the wrong method can impact performance, especially in loops or frequently executed code paths. It also makes the code less clear about its intent - when you see test(), it’s immediately obvious that only a boolean result is needed.

What is the potential impact?

Using String.match() or RegExp.exec() instead of RegExp.test() for boolean checks creates unnecessary performance overhead through extra memory allocation and processing. In performance-critical code or loops, this can lead to measurable slowdowns and increased memory usage.

How to fix?

Replace String.match() calls with RegExp.test() when used in boolean contexts. Move the regular expression to the left side and call test() with the string as an argument.

Non-compliant code example

if (string.match(/unicorn/)) {
  // do something
} // Noncompliant

Compliant code example

if (/unicorn/.test(string)) {
  // do something
}

Documentation