Importance of JavaScript Exec method for pattern matching in regular expressions

A different and great solution to a very famous interview question

Yogesh Chavan
Dec 6, 2019 · 3 min read
Photo by Rachel Danner on Unsplash

The regular expressions are great for finding patterns in a string for particular match.They helps us to convert the complex logic into short and easy to understand code.
Today we will see one such great method for pattern matching in javascript which is exec method.

It has following syntax

regexObj.exec(string)

Before getting into the the actual question, let’s understand what is exec and what it does.

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

The pattern also maintains a lastIndex property which is the index at which it will start searching for next match once it founds a particular match.

Lets understand through an example.

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 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);
/* outputi 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 next match considering the index counting starts with zero instead of 1.

Now get started with the actual interview question.
The question goes like this

Write a Program which will print how many times a word is present in a particular string and also print the index of where its found.

Let’s start with it

Suppose, we want to check how many times 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);
/* outputhappy 7
happy 43
happy 82
happy 109
Total Occurrences: 4
*/

But there is one issue in the above code, we are directly hardcoding the text happy in the pattern as
const pattern = /happy/g;

But if the text to search is not known in advance, we can use the RegExp constructor of regular expression to achieve the same thing as 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);
/* outputhappy 7
happy 43
happy 82
happy 109
Total Occurrences: 4
*/

In the above code, we have just changed:

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

Instead of:

const pattern = /happy/g;

So now you can store the dynamic text to search for in the string variable and use it as first parameter of RegExp constructor.

That’s it for today, Hope you learned something new today.

Subscribe to get weekly updates directly in your inbox https://subscribe-user.herokuapp.com/

JavaScript in Plain English

Learn the web's most important programming language.

Yogesh Chavan

Written by

Full Stack Developer | Javascript | React | Nodejs. Subscribe to get weekly updates directly in your inbox https://subscribe-user.herokuapp.com/

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade