var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
更新
我在原始问题中未能发现搜索字符串必须是变量。我写了另一个版本来处理这种情况,它使用,所以你回到了你开始的地方。正如Wrikken在评论中指出的那样,要对正则表达式的一般情况执行此操作,您需要转义特殊的正则表达式字符,此时我认为正则表达式解决方案变得更加令人头疼,而不是它的价值。indexOf
function getIndicesOf(searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>