Importance of JavaScript Exec Method In JavaScript

Regular expressions are great for finding patterns in a string for a particular match. They help us to convert complex logic into short and easy-to-understand code.

Today we will see one such great method for pattern matching in JavaScript which is the exec method.

We will also see some code examples where exec is really helpful.

So let’s get started.

What Is the exec Method

The exec method has the following syntax:

regexObj.exec(string)

Let’s understand what is the use of exec method.

The exec method is similar to the match method of regular expression which returns an array of matches found if successful otherwise returns null.

But in the case of exec, the pattern also maintains a lastIndex property which is the index at which it will start searching for the next match once it finds a particular match.

Suppose, we want to find all the occurrences of vowels in the string and also the position of the match, we can do it as shown below:

const text = "This is a simple text";
const pattern = /[aeiou]/g;
let output = "";
while((result = pattern.exec(text)) !== null) {
 output += result[0] + " " + pattern.lastIndex + "\n";
}
console.log(output);

/* output

i 3
i 6
a 9
i 12
e 16
e 19
*/

As you can see from the output, the index printed is not the index of the match but the index from which it will start searching for the next match considering the index counting starts with zero instead of 1.

There is a popular interview question where exec is really useful.

The question goes like this:

Write a code that will print how many times a word is present in a particular string and also print the index of where it’s found.

Suppose, we want to check how many times the word happy is present in the string we can do that as shown below:

const str = "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn't really happy.";
const pattern = /happy/g;
let count = 0;
while((result = pattern.exec(str)) !== null) {
 count++;
 console.log(result[0], pattern.lastIndex - result[0].length);
}

console.log("Total Occurrences:", count);

/* output

happy 7
happy 43
happy 82
happy 109
Total Occurrences: 4
*/

But what If we don’t know in advance the word to search for or If the word is a user-entered value in the textbox?

In that case, we can use the RegExp constructor of a regular expression to achieve the same thing as shown below:

const str = "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy.";
const string = "happy";
const pattern = new RegExp(string,"g");
let count = 0;
while((result = pattern.exec(str)) !== null) {
 count++;
 console.log(result[0], pattern.lastIndex - result[0].length);
}

console.log("Total Occurrences:", count);

/* output

happy 7
happy 43
happy 82
happy 109
Total Occurrences: 4
*/

In the above code, we have just changed the below code:

const pattern = /happy/g;

to this code:

const string = "happy";
const pattern = new RegExp(string, "g");

Thanks for reading!

As you can see, the exec method is really useful If we want to maintain the position of the last search.

Check out my recently published Mastering Redux course.

In this course, you will build 3 apps along with food ordering app and you’ll learn:

  • Basic and advanced Redux
  • How to manage the complex state of array and objects
  • How to use multiple reducers to manage complex redux state
  • How to debug Redux application
  • How to use Redux in React using react-redux library to make your app reactive.
  • How to use redux-thunk library to handle async API calls and much more

and then finally we’ll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.

Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.

Yogesh Chavan
Freelancer and a Full Stack Developer with 9+ years of professional experience in designing, developing, and maintaining amazing web applications and websites using React, JavaScript, Node.js, HTML and CSS.

Related Articles

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on Top - Get the daily news in your inbox