Gadi A Gadi A -4 years ago 132
Javascript Question

How to get all indexes of a pattern in a string?

I want something like this:

"abcdab".search(/a/g) //return [0,4]


Is it possible?

Answer Source

You can use the RegExp#exec method several times:

var regex = /a/g;
var str = "abcdab";

var result = [];
var match;
while (match = regex.exec(str))
   result.push(match.index);

alert(result);  // => [0, 4]

Helper function:

function getMatchIndices(regex, str) {
   var result = [];
   var match;
   regex = new RegExp(regex);
   while (match = regex.exec(str))
      result.push(match.index);
   return result;
}

alert(getMatchIndices(/a/g, "abcdab"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download