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

查看:41
本文介绍了如何在 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天全站免登陆