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);
}
更新
我未能在原始问题中发现搜索字符串需要是一个变量。我编写了另一个版本来处理使用的这种情况
indexOf,因此您回到了起点。正如Wrikken在评论中所指出的那样,要对具有正则表达式的一般情况执行此 *** 作,您需要转义特殊的正则表达式字符,这时我认为正则表达式解决方案变得比其价值更令人头疼。
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>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)