正如您发布的 StackOverflow 链接中的答案所示,您可以使用第二个参数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/