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
.
RegExpObject.test(string)
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 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.
/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.
cat
is present in the string of Educative,
so test
returns true
.CAT
is present, but we haven’t added the i
modifier to be case insensitive, so test
returns false
.ive1
is not present in the string of Educative,
so test
returns false
.