如何在JavaScript中找到一个字符串在另一个字符串中所有出现的索引?

我试图在不区分大小写的另一个字符串中查找一个字符串所有出现的位置。

例如,给定字符串:

我学会了在黎巴嫩玩四弦琴。

和搜索字符串le,我想获取数组:

[2, 25, 27, 33]

这两个字符串都是变量-即,我无法对它们的值进行硬编码。

我认为对于正则表达式来说这是一件容易的事,但是在努力寻找一个可行的表达式后,我却没有运气。

我找到了使用来完成此操作的示例.indexOf(),但是肯定有一种更简洁的方法可以完成此操作吗?

回答:

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>

以上是 如何在JavaScript中找到一个字符串在另一个字符串中所有出现的索引? 的全部内容, 来源链接: utcz.com/qa/417682.html

回到顶部