var regex = /a/g;
var str = "abcdab";
var result = [];
var match;
while (match = regex.exec(str))
result.push(match.index);
alert(result); // => [0, 4]
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"));
var str = "abcdab";
var re = /a/g;
var matches;
var indexes = [];
while (matches = re.exec(str)) {
indexes.push(matches.index);
}
// indexes here contains all the matching index values
Another non-regex solution:
A non-regex variety:
http://jsfiddle.net/userdude/HUm8d/
If you only want to find simple characters, or character sequences, you can use
indexOf
[MDN]:You can use the
RegExp#exec
method several times:Helper function:
You can get all match indexes like this:
Working demo here: http://jsfiddle.net/jfriend00/r6JTJ/
You could use / abuse the replace function:
The arguments to the function are as follows: