Use of exec() Regex Method in JavaScript



exec()

The exec() method is a regex method. It searches a string for a specified pattern and, unlike test() regex method, returns the found text as an object. If there are no matches it will give null as an output. Let's discuss it in detail.

Example-1

In the following example, a variable pattern "est" is checked through the exec() method. The exec() regex method, after scrutinizing the given pattern throughout the text, returned the pattern as an object.

Live Demo

<html>
<body>
<script>
   var obj = /est/.exec("Tutorix is the best e-learning platform");
   document.write(
   "The object is " + obj[0] + " and its position is " + obj.index);
</script>
</body>
</html>

Output

The object is est and its position is 16

Example-2

In the following example, a variable pattern "x" is checked through the exec() method. The exec() regex method, after scrutinizing the given pattern throughout the text, returned the pattern as an object.

Live Demo

<html>
<body>
<script>
   var obj = /x/.exec("Tutorix is the best e-learning platform");
   document.write(
   "The object is " + obj[0] + " and its position is " + obj.index);
</script>
</body>
</html>

Output

The object is x and its position is 6
Updated on: 2019-07-30T22:30:26+05:30

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements