Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript exec() Method

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 26 Dec, 2022
Improve Article
Save Article

The exec() Method in JavaScript is used to test for the match in a string. If there is a match this method returns the first match else it returns NULL.

Syntax:

RegExpObject.exec(str)

Parameters:

  • str: It is the string to be searched. This is a required field. 

Return value:

  • This method returns an array that contains the matched text if the match is found, else it returns null.

Example 1: This example searches for the string “computer” in the original string. 
 

html




<body style="text-align:center">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h2>exec() 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", );
            // match "computer" in string.                       
            var rex = regex.exec(str);
            document.getElementById("app").innerHTML =
                " Found " + rex.length + " match: " + rex;
        }
    </script>
</body>

Output: 

 

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

html




<body style="text-align:center">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h2>
        exec() 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("rep");
            
            // Match "rep" in string.
            var rex = regex.exec(str);
            alert(rex);
        }
    </script>
</body>

Output: 

 

We have a complete list of Javascript Functions, to check those go through the Javascript Functions Complete Reference article.

Supported Browsers: The browsers supported by the JavaScript exec() Method are listed below: 

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!