Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

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 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

Reported:

if (email.match(/@/)) {
  send(email);
}

const isHex = Boolean(/^[0-9a-f]+$/i.exec(color));

const label = !name.match(/\S/) ? "(empty)" : name;

Not reported:

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 changed:

  • text.match(pattern) also accepts a string in pattern, and a string has no test() method.
  • A regular expression with the g flag remembers where the last test() stopped. text.match(pattern) always starts at the beginning.