Return positions of a regex match() in Javascript?

stagas picture stagas · Feb 19, 2010 · Viewed 117.7k times · Source

Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?

Answer

Gumbo picture Gumbo · Feb 19, 2010

exec returns an object with a index property:

var match = /bar/.exec("foobar");
if (match) {
    console.log("match found at " + match.index);
}

And for multiple matches:

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}