For AI agents: the complete documentation index is available at https://rslint.rs/llms.txt, the full documentation bundle is available at https://rslint.rs/llms-full.txt, and this page is available as Markdown at https://rslint.rs/rules/unicorn/prefer-regexp-test.md.
close

prefer-regexp-test

Added in v0.10.1

Configuration

rslint.config.ts
import { defineConfig, unicornPlugin } from '@rslint/core';

export default defineConfig([
  unicornPlugin.configs.recommended,
  {
    rules: {
      'unicorn/prefer-regexp-test': 'error',
    },
  },
]);

Rule details

Prefer RegExp#test() over String#match(), String#search(), and RegExp#exec() when only checking whether a pattern matches.

Examples of incorrect code for this rule:

if (string.match(/unicorn/)) {}
if (/unicorn/.exec(string)) {}
if (string.match(/unicorn/).length > 0) {}
if (string.search(/unicorn/) !== -1) {}

Examples of correct code for this rule:

if (/unicorn/.test(string)) {}

The rule recognizes boolean contexts and comparisons of search() results with -1 or 0. Calls with known incompatible receivers or arguments are ignored.

Static regular expressions without the g flag can be fixed automatically. For search(), the y flag also prevents automatic fixes. Unknown expressions and expressions with these flags receive suggestions. Positive .length checks receive suggestions because replacing them can change how a failed match is handled. Comments that would be removed prevent the fix or suggestion.

Options

This rule has no options.

Differences from upstream

Expressions inside Vue and Svelte templates are not checked. Expressions in JavaScript, JSX, and TypeScript files are checked.

String intersections that resolve to string, such as string & unknown, are treated as strings. The following call is left unchanged instead of receiving a suggestion to use .test():

function f(pattern: string & unknown) {
  if (text.match(pattern)) {}
}

Regular expressions with modified properties or uses of compile() receive suggestions instead of automatic fixes, including when a variable alias is used. Changing matching hooks or flags can make .test() return different results:

const re = /x/;
re.compile('x', 'g');
if ('x'.match(re)) {}

Original documentation