regexTestMethods
Reports match() and exec() calls that should use RegExp.prototype.test() for boolean checks.
✅ This rule is included in the tsstylisticandstylisticStrictpresets.
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 aboolean, 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.
Examples
Section titled “Examples”Using exec() in a Condition
Section titled “Using exec() in a Condition”if (pattern.exec(text)) { console.log("found");}if (pattern.test(text)) { console.log("found");}Using match() in a Condition
Section titled “Using match() in a Condition”if (text.match(/search/)) { console.log("found");}if (/search/.test(text)) { console.log("found");}Negation
Section titled “Negation”const notFound = !text.match(/pattern/);const notFound = !/pattern/.test(text);Global Flag (No Fix)
Section titled “Global Flag (No Fix)”When the regex has a global flag, the rule reports but does not auto-fix because .test() behavior differs:
// Reports but does not auto-fixif (text.match(/pattern/g)) {}Using Results (Valid)
Section titled “Using Results (Valid)”Using the result of exec() or match() is valid:
const matches = text.match(/(\w+)/);const group = pattern.exec(text)?.[1];Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.