Skip to content

regexTestMethods

Reports match() and exec() calls that should use RegExp.prototype.test() for boolean checks.

✅ This rule is included in the ts stylistic presets.

Two common regular expression methods exist for checking whether a pattern exists in a string:

  • exec(): returns a full matches array, including capture groups, which requires more work than just boolean checking.
  • test(): only returns a boolean, which is more efficient and semantically clearer when only checking for pattern existence.

This rule reports calls to String.prototype.match() and RegExp.prototype.exec() that are used in a boolean context.

if (pattern.exec(text)) {
console.log("found");
}
if (text.match(/search/)) {
console.log("found");
}
const notFound = !text.match(/pattern/);

When the regex has a global flag, the rule reports but does not auto-fix because .test() behavior differs:

// Reports but does not auto-fix
if (text.match(/pattern/g)) {
}

Using the result of exec() or match() is valid:

const matches = text.match(/(\w+)/);
const group = pattern.exec(text)?.[1];

This rule is not configurable.

If you prefer the semantics of exec() or match() even in boolean contexts, you might prefer to disable this rule. For example, some developers prefer to always use the same methods for stylistic consistency.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.