Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript RegExp test() Method

Improve Article
Save Article
Like Article
  • Last Updated : 06 Jan, 2023
Improve Article
Save Article
Like Article

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.  

html




<h1 style="color:green">
    GeeksforGeeks
</h1>
  
<h2>test() Method</h2>
  
  
<p>
    String: GeeksforGeeks is the
    computer science 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>

Output: 

JavaScript RegExp test() Method

JavaScript RegExp test() Method

Example 2: This example searches for the string “GEEK” in the original string. 
 

html




<h1 style="color:green">
    GeeksforGeeks
</h1>
  
<h2>test() Method</h2>
  
  
<p>
    String: GeeksforGeeks is the
    computer science 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>

Output: 

JavaScript RegExp test() Method

JavaScript RegExp test() Method

Supported Browsers: The browsers supported by RegExp test() Method are listed below: 
 

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Internet Explorer

We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Complete Reference article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.  


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!