JavaScript | exec() Method
The exec() Method in JavaScript is used to test for match in a string. If there is a match this method returns the first match else it returns NULL.
Syntax:
RegExpObject.exec(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> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>exec() 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", ); // match "computer" in string. var rex = regex.exec(str); document.getElementById("app").innerHTML = " Found " + rex.length + " match: " + rex; } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Example-2: This example searches for the string “rep” in the original string.
<!DOCTYPE html> <html> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> exec() 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("rep"); // Match "rep" in string. var rex = regex.exec(str); alert(rex); } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Supported Browsers: The browsers supported by JavaScript exec() Method are listed below:
- Google Chrome
- Apple Safari
- Mozilla Firefox
- Opera
- Internet Explorer
Recommended Posts:
- PHP | shell_exec() vs exec() Function
- JavaScript | Sort() method
- JavaScript | Replace() Method
- JavaScript | compile() Method
- JavaScript | getTime() Method
- JavaScript | Array from() Method
- JavaScript | Array map() Method
- JavaScript | Array.from() method
- JavaScript | RegExp toString() Method
- JavaScript | clearTimeout() & clearInterval() Method
- JavaScript | String includes() Method
- JavaScript | Array reduce() Method
- JavaScript | date.getMinutes() Method
- JavaScript | String startsWith() Method
- JavaScript | Array.join() Method
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.



