Computer >> Computer tutorials >  >> Programming >> Javascript

What is the 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.

<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.

<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