The test()
method in JavaScript’s RegExp object is used to test if a string matches a regular expression pattern.
It returns a boolean value indicating whether or not the string matches the pattern.
Here’s an example of using the test()
method to check if a string contains the word "hello"
:
const str = "Hello world!";
const regex = /hello/i;
const result = regex.test(str);
console.log(result); // true
In this example, the regular expression /hello/i
is created with the i
flag to make it case-insensitive. The test()
method is then called on the regex object with the str
string as the argument. Since the string contains the word "Hello"
, which matches the pattern, the test()
method returns true.
Here’s another example of using the test()
method to validate an email address:
const email = "example@example.com";
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const result = regex.test(email);
console.log(result); // true
In this example, the regular expression /^[^\s@]+@[^\s@]+\.[^\s@]+$/
is created to match the format of a typical email address. The test()
method is then called on the regex object with the email
string as the argument. Since the string matches the pattern, the test()
method returns true
.
The test()
method can also be used in a loop to find all occurrences of a pattern in a string.
Here’s an example of using the test()
method in a loop to find all instances of the word "hello"
in a string:
const str = "hello world, hello there";
const regex = /hello/gi;
let match;
while ((match = regex.exec(str))) {
console.log(`Found '${match[0]}' at position ${match.index}`);
}
In this example, the regular expression /hello/gi
is created with the g
flag to match all occurrences of the pattern and the i
flag to make it case-insensitive. The test()
method is then called in a loop using the exec()
method on the regex object with the str
string as the argument. The loop continues until there are no more matches, and for each match, the index of the match is logged to the console.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.