What is the regex.test() method in JavaScript?

Definition

The regex.test() method is used to test for a match in a string. The method returns true if it finds a match; otherwise, it returns false.

Syntax

 RegExpObject.test(string)

Syntax overview

The RegExpObject class deals with regular expressions. Both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.

Example

// Example 1
console.log("Matching String : ",/cat/i.test('Educative'));
// Example 2
console.log("Case Sensitive : ",/CAT/.test('Educative'));
// Example 3
console.log("Non-Matching String : ",/ive1/.test('Educative'));

In the example above, we use the test method to determine if there is a match. test will return the result as a Boolean value.

Explanation

  • /cat/i is a regular expression.
  • cat is a pattern to be used in a search.
  • i is a modifier that allows the search to be case-insensitive.
  • In Example 1, cat is present in the string of Educative, so test returns true.
  • In Example 2, CAT is present, but we haven’t added the i modifier to be case insensitive, so test returns false.
  • In Example 3, ive1 is not present in the string of Educative, so test returns false.

Free Resources