As the answer in the StackOverflow link you posted shows, you can use the second parameter of indexOf
to define where the search starts in the string. You can continue looping over the string, using this technique, to get the indexes of all matched substrings:
function getMatchIndexes(str, toMatch) {
var toMatchLength = toMatch.length,
indexMatches = [], match,
i = 0;
while ((match = str.indexOf(toMatch, i)) > -1) {
indexMatches.push(match);
i = match + toMatchLength;
}
return indexMatches;
}
console.log(getMatchIndexes("asdf asdf asdf", "as"));
DEMO: http://jsfiddle.net/qxERV/
Another option is to use a regular expression to find all matches:
function getMatchIndexes(str, toMatch) {
var re = new RegExp(toMatch, "g"),
indexMatches = [], match;
while (match = re.exec(str)) {
indexMatches.push(match.index);
}
return indexMatches;
}
console.log(getMatchIndexes("asdf asdf asdf", "as"));
DEMO: http://jsfiddle.net/UCpeY/
And yet another option is to manually loop through the string's characters and compare to the target:
function getMatchIndexes(str, toMatch) {
var re = new RegExp(toMatch, "g"),
toMatchLength = toMatch.length,
indexMatches = [], match,
i, j, cur;
for (i = 0, j = str.length; i < j; i++) {
if (str.substr(i, toMatchLength) === toMatch) {
indexMatches.push(i);
}
}
return indexMatches;
}
console.log(getMatchIndexes("asdf asdf asdf", "as"));
DEMO: http://jsfiddle.net/KfJ9H/