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 1console.log("Matching String : ",/cat/i.test('Educative'));// Example 2console.log("Case Sensitive : ",/CAT/.test('Educative'));// Example 3console.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/iis a regular expression.catis a pattern to be used in a search.iis a modifier that allows the search to be case-insensitive.
- In Example 1,
catis present in the string ofEducative,sotestreturnstrue. - In Example 2,
CATis present, but we haven’t added theimodifier to be case insensitive, sotestreturnsfalse. - In Example 3,
ive1is not present in the string ofEducative,sotestreturnsfalse.