JavaScript RegExp test()
Syntax & Examples

RegExp.test() method

The test() method of the RegExp object in JavaScript tests for a match in a specified string. This method returns true if it finds a match, otherwise it returns false.


Syntax of RegExp.test()

The syntax of RegExp.test() method is:

test(str)

This test() method of RegExp tests for a match in its string parameter. Returns true if a match is found, otherwise returns false.

Parameters

ParameterOptional/RequiredDescription
strrequiredThe string against which to match the regular expression.

Return Type

RegExp.test() returns value of type Boolean.



✐ Examples

1 Using test() to check for a pattern in a string

In JavaScript, we can use the test() method to check if a pattern exists in a string.

For example,

  1. We create a RegExp object regex with the pattern /hello/.
  2. We use the test() method to check if the pattern exists in the string 'hello world'.
  3. The result is stored in the variable result and we log it to the console.

JavaScript Program

const regex = /hello/;
const result = regex.test('hello world');
console.log(result);

Output

true

2 Using test() with a case-insensitive pattern

In JavaScript, we can use the test() method with the 'i' flag to perform a case-insensitive match.

For example,

  1. We create a RegExp object regex with the pattern /hello/i for case-insensitive matching.
  2. We use the test() method to check if the pattern exists in the string 'Hello World'.
  3. The result is stored in the variable result and we log it to the console.

JavaScript Program

const regex = /hello/i;
const result = regex.test('Hello World');
console.log(result);

Output

true

3 Using test() to check for digits in a string

In JavaScript, we can use the test() method to check if a string contains digits.

For example,

  1. We create a RegExp object regex with the pattern /\d+/ to match one or more digits.
  2. We use the test() method to check if the pattern exists in the string 'abc123'.
  3. The result is stored in the variable result and we log it to the console.

JavaScript Program

const regex = /\d+/;
const result = regex.test('abc123');
console.log(result);

Output

true

Summary

In this JavaScript tutorial, we learned about test() method of RegExp: the syntax and few working examples with output and detailed explanation for each example.