JavaScript RegExp test() Method

The JavaScript test() method is used when we need to search a string for match against a regular expression. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="res"></p>

   <script>
      let myString = "I live in St. Louis";
      let pattern = /i/;
      document.getElementById("res").innerHTML = pattern.test(myString);
   </script>
   
</body>
</html>
Output

JavaScript test() Syntax

The syntax of test() method in JavaScript is:

RegExpObj.test(x)

where x refers to a string to be searched. The test() method returns a boolean value (true/false). It returns true if match available, otherwise returns false. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Searching for "ive": <span id="resOne"></span></p>
   <p>Searching for "ing": <span id="resTwo"></span></p>

   <script>
      let myString = "I live in St. Louis";
      let patternOne = /ive/;
      let patternTwo = /ing/;
      document.getElementById("resOne").innerHTML = patternOne.test(myString);
      document.getElementById("resTwo").innerHTML = patternTwo.test(myString);
   </script>
   
</body>
</html>
Output

Searching for "ive":

Searching for "ing":

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋