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

test() is sometimes written as RegExp.prototype.test() because it is a method of the RegExp object's prototype property.

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

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

Test if a string contains @

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

// The invocation above will return: false

Try Editing It

Overview

RegExp test() method's
tidbit

Use RegExp's test() method to test if a string contains a regular expression pattern.

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

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Join CodeSweetly Newsletter