JavaScript | RegExp test() Method
The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false.
Syntax:
RegExpObject.test(str)
Where str is the string to be searched. This is required field.
Example 1: This example searches for the string “computer” in the original string.
<!DOCTYPE html> <html> <head> <title> JavaScript RegExp test() Method </title> </head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>test() Method</h2> <p> String: GeeksforGeeks is the computer scince portal for geeks. </p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <script> function geek() { var str="GeeksforGeeks is the computer science" + " portal for geeks."; var regex = new RegExp("computer", ); var rex = regex.test(str); document.getElementById("app").innerHTML = " Match " + " found: " + "<b>" + rex + "</b>"; } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Example 2: This example searches for the string “GEEK” in the original string.
<!DOCTYPE html> <html> <head> <title> JavaScript RegExp test() Method </title> </head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>test() Method</h2> <p> String: GeeksforGeeks is the computer scince portal for geeks. </p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <script> function geek() { var str="GeeksforGeeks is the computer science" + " portal for geeks."; var regex = new RegExp("GEEK", ); var rex = regex.test(str); document.getElementById("app").innerHTML = " Match " + " found: " + "<b>" + rex + "</b>"; } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Supported Browsers: The browsers supported by RegExp test() Method are listed below:
- Google Chrome
- Apple Safari
- Mozilla Firefox
- Opera
- Internet Explorer
Recommended Posts:
- JavaScript | RegExp toString() Method
- JavaScript | RegExp \xxx Metacharacter
- JavaScript | RegExp \b Metacharacter
- JavaScript | RegExp [^abc] Expression
- JavaScript | RegExp {X,} Quantifier
- JavaScript | RegExp \w Metacharacter
- JavaScript | RegExp constructor
- JavaScript | RegExp \d Metacharacter
- JavaScript | RegExp . Metacharacter
- JavaScript | RegExp \W Metacharacter
- JavaScript | RegExp ? Quantifier
- JavaScript | RegExp + Quantifier
- JavaScript | RegExp \0 Metacharacter
- JavaScript | RegExp \r Metacharacter
- JavaScript | RegExp {X} Quantifier
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



