Sometimes, we want to find the index of the regex match in our JavaScript code.
In this article, we’ll look at how to find the index of a regex match with JavaScript.
Use the RegExp.prototype.exec Method
We can use the JavaScript regex’s exec
method to find the index of a regex match.
For instance, we can write:
const match = /bar/.exec("foobar");
console.log(match && match.index);
We call exec
on /bar/
with 'foobar'
as the argument to find the bar
pattern in the 'foobar'
string.
If match
isn’t null
, then it should have the match.index
property with the first index of the matched substring in the 'foobar'
string.
Since 'bar'
starts at index 3, match.index
should be 3.
We can also use it to get the index of all the matches in a string.
For instance, we can write:
const re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) !== null) {
console.log(match && match.index);
}
re
has the g
flag to let us search for all the matches of a pattern in a string.
We loop through the results returned by re.exec
with the while
loop.
If the returned result isn’t null
, then we keep getting the matched results until it returns null
.
match.index
therefore should be 3 and 9 since the first 'bar'
starts at index 3 and the 2nd 'bar'
starts at index 9.
Conclusion
We can find the indexes of one or more matches of a regex pattern within a JavaScript string by using the RegExp.prototype.exec
method.