# 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)`.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-regexp-test" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 3} */}
```js
if (email.match(/@/)) {
  send(email);
}

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

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

Not reported:

{/* good */}
```js
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:

{/* good */}
```js
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.
