如何在JavaScript中查找一个字符串中所有出现的索引? [英] How to find indices of all occurrences of one string in another in JavaScript?

查看:89
本文介绍了如何在JavaScript中查找一个字符串中所有出现的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find the positions of all occurrences of a string in another string, case-insensitive.

例如,给定字符串:

I learned to play the Ukulele in Lebanon.

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

and the search string le, I want to obtain the array:

[2, 25, 27, 33]

这两个字符串都是变量 - 即我不能硬编码它们的值。

Both strings will be variables - i.e., I can't hard-code their values.

我认为对于正则表达式来说这是一个简单的任务,但经过一段时间的努力找到一个可行的表达式后,我没有运气。

I figured that this was an easy task for regular expressions, but after struggling for a while to find one that would work, I've had no luck.

我发现这个例子如何使用 .indexOf()完成此操作,但肯定有更简洁的方法来做到这一点?

I found this example of how to accomplish this using .indexOf(), but surely there has to be a more concise way to do it?

推荐答案

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在评论中指出的那样,对于使用正则表达式的一般情况,你需要转义特殊的正则表达式字符,此时我认为正则表达式解决方案变得更加令人头疼而不是它的价值。

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

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中查找一个字符串中所有出现的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆