unicorn/prefer-regexp-test
Require RegExp#test() instead of String#match() and RegExp#exec() for a yes or no answer
match() and exec() build an array with the match and its groups. When you only want to know whether the text matches, test() returns a boolean and skips that work.
The rule reports match() and exec() where only true or false matters: the condition of if, while, do, for and ? :, after !, and inside Boolean().
--fix rewrites pattern.exec(text) to pattern.test(text) if the file shows that pattern is a regular expression: a literal, new RegExp(), or a variable that's declared with one and never assigned again. It rewrites text.match(pattern) if pattern is a literal without the g flag and text is visibly a string. --fix-dangerously rewrites the rest.
Configure#
Off by default. To turn it on:
[lint.rules]
"unicorn/prefer-regexp-test" = "error" # or "warn"Examples#
if (email.matchPrefer RegExp#test() over String#match() and RegExp#exec().(/@/)) {
send(email);
}
const isHex = Boolean(/^[0-9a-f]+$/i.execPrefer RegExp#test() over String#match() and RegExp#exec().(color));
const label = !name.matchPrefer RegExp#test() over String#match() and RegExp#exec().(/\S/) ? "(empty)" : name;if (/@/.test(email)) {
send(email);
}
const isHex = /^[0-9a-f]+$/i.test(color);
const label = !/\S/.test(name) ? "(empty)" : name;Nothing is reported where you use the match itself:
const found = version.match(/^(\d+)\./);
const major = found ? found[1] : "0";When not to use it#
The rule doesn't know types, so check what --fix-dangerously changed:
text.match(pattern)also accepts a string inpattern, and a string has notest()method.- A regular expression with the
gflag remembers where the lasttest()stopped.text.match(pattern)always starts at the beginning. - Other objects have an
exec()method too, like a database.