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.
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.
Parameter | Optional/Required | Description |
---|---|---|
str | required | The string against which to match the regular expression. |
RegExp.test() returns value of type Boolean
.
In JavaScript, we can use the test()
method to check if a pattern exists in a string.
For example,
regex
with the pattern /hello/
.test()
method to check if the pattern exists in the string 'hello world'
.result
and we log it to the console.const regex = /hello/;
const result = regex.test('hello world');
console.log(result);
true
In JavaScript, we can use the test()
method with the 'i' flag to perform a case-insensitive match.
For example,
regex
with the pattern /hello/i
for case-insensitive matching.test()
method to check if the pattern exists in the string 'Hello World'
.result
and we log it to the console.const regex = /hello/i;
const result = regex.test('Hello World');
console.log(result);
true
In JavaScript, we can use the test()
method to check if a string contains digits.
For example,
regex
with the pattern /\d+/
to match one or more digits.test()
method to check if the pattern exists in the string 'abc123'
.result
and we log it to the console.const regex = /\d+/;
const result = regex.test('abc123');
console.log(result);
true
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.