投稿したStackOverflowリンクの回答が示すように、の2番目のパラメーターを使用indexOf
して、文字列内で検索を開始する場所を定義できます。この手法を使用して文字列をループし続けると、一致したすべての部分文字列のインデックスを取得できます。
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"));
デモ: http://jsfiddle.net/qxERV/
別のオプションは、正規表現を使用してすべての一致を見つけることです。
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"));
デモ: http://jsfiddle.net/UCpeY/
さらに別のオプションは、文字列の文字を手動でループし、ターゲットと比較することです。
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"));
デモ: http://jsfiddle.net/KfJ9H/