Skip to main content

test() JavaScript RegExp Method – How to Test a String

Whenever you use test() on a regular expression, the method does the following:

  1. It tests its string argument for the regular expression's pattern.
  2. It returns true if it finds the RegExp pattern in the string. Otherwise, it returns false.

Syntax of the test() Method

test() accepts a string argument. Here is the syntax:

RegExp.test("stringToTest");

Examples

Below are examples of the test() method.

Test a string for a case-insensitive Color pattern

/Color/i.test("My best color is blue.");

// The invocation above will return:
true;

Try it on StackBlitz

The snippet above returned true because the computer found the RegExp pattern in the string argument.

In other words, the test for a case-insensitive Color pattern in the string argument matched the string's color text. Therefore, test() returned true.

Test if Sweetly is at the end of "CodeSweetly"

/Sweetly$/.test("CodeSweetly");

// The invocation above will return:
true;

Try it on StackBlitz

Test if a string contains @

/@/.test("Learn JavaScript at codesweetly.com");

// The invocation above will return:
false;

Try it on StackBlitz

Overview

test() tests its string argument for an occurrence of a regular expression.

If you like this article, please Tweet it.

Thanks for reading!