unicorn/prefer-regexp-test
Require RegExp#test() instead of String#match() and RegExp#exec() for a yes or no answer
fixable
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 both text.match(pattern) and pattern.exec(text) to pattern.test(text).
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-regexp-test" = "error" # or "warn"Examples#
example.js3 problems
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;example.jsNo problems
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:
example.jsNo problems
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 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.