【问题标题】:Looping Through String To Find Multiple Indexes遍历字符串以查找多个索引
【发布时间】:2013-05-29 15:57:25
【问题描述】:

我正在尝试找出循环遍历字符串并查找某个字母的所有索引的最有效方法。

我曾使用$word_or_phrase.indexOf( $letter ); 查找一个字母的单个索引,但该字母多次出现在$word_or_phrase 中。最有效的方法是构建一个包含所有索引的数组,直到.indexOf 返回-1?或者你会建议我如何找到所有的索引?

我已经花时间找到了这个: Javascript str.search() multiple instances

这可行,但对我来说,在处理超过 2 个索引时似乎效率不高。如果我有 10 个呢?

提前感谢您的建议!

【问题讨论】:

  • 感谢大家的快速和有用的建议。回答这个问题的贡献绰绰有余,这篇文章将来肯定会对某人有所帮助。

标签: javascript jquery loops indexing indexof


【解决方案1】:

正如您发布的 StackOverflow 链接中的答案所示,您可以使用 indexOf 的第二个参数来定义搜索在字符串中的开始位置。您可以使用此技术继续循环遍历字符串,以获取所有匹配子字符串的索引:

function getMatchIndexes(str, toMatch) {
    var toMatchLength = toMatch.length,
        indexMatches = [], match,
        i = 0;

    while ((match = str.indexOf(toMatch, i)) > -1) {
        indexMatches.push(match);
        i = match + toMatchLength;
    }

    return indexMatches;
}

console.log(getMatchIndexes("asdf asdf asdf", "as"));

演示: http://jsfiddle.net/qxERV/

另一种选择是使用正则表达式来查找所有匹配项:

function getMatchIndexes(str, toMatch) {
    var re = new RegExp(toMatch, "g"),
        indexMatches = [], match;

    while (match = re.exec(str)) {
        indexMatches.push(match.index);
    }

    return indexMatches;
}

console.log(getMatchIndexes("asdf asdf asdf", "as"));

演示: http://jsfiddle.net/UCpeY/

另一种选择是手动循环遍历字符串的字符并与目标进行比较:

function getMatchIndexes(str, toMatch) {
    var re = new RegExp(toMatch, "g"),
        toMatchLength = toMatch.length,
        indexMatches = [], match,
        i, j, cur;

    for (i = 0, j = str.length; i < j; i++) {
        if (str.substr(i, toMatchLength) === toMatch) {
            indexMatches.push(i);
        }
    }

    return indexMatches;
}

console.log(getMatchIndexes("asdf asdf asdf", "as"));

演示: http://jsfiddle.net/KfJ9H/

【讨论】:

    【解决方案2】:

    可能是一个解决方案:

    http://jsfiddle.net/HkbpY/

    var str = 'some kind of text with letter e in it',
        letter = 'e',
        indexes = [];
    
    $.each(str.split(''),function(i,v){
        if(v === letter) indexes.push(i);
    });
    
    console.log(indexes);
    

    【讨论】:

    • 您如何找到例如“ea”?我的意思是你只能找到一个字母的匹配项。两个以上怎么办?
    • @pokekart2002 考虑提出一个新问题
    【解决方案3】:

    检查一下...

    var data = 'asd 111 asd 222 asd 333';
    var count = countOccurence('asd', data);
    console.info(count);
    function countOccurence(item, data, count){
        if (count == undefined) { count = 0; }
        if (data.indexOf(item) != -1)
        {
            count = count+1;
            data = data.substring(data.indexOf(item) + item.length);
            count = countOccurence(item, data, count);
        }
        return count;
    }
    

    【讨论】:

    • 感谢您的回复!
    【解决方案4】:
    var mystring = 'hello world';
    var letterToCount = 'l';
    
    var indexes = [];
    for(var i=0; i<mystring.length; i++) {
        if(mystring[i] == letterToCount)
           indexes.push(i); 
    }
    
    alert(indexes.join(',')); //2,3,9
    

    【讨论】:

    • 感谢 sjkm 的快速响应,但是,这并没有给出索引,而是给出了字母存在的次数。在您的示例中,我希望输出是发生次数 = 3,4,9。我没有对你投反对票。
    • 请执行上面的代码...它返回的正是你想要的^^
    【解决方案5】:

    这样试试

    var str = "foodfoodfoodfooooodfooooooood";
    for (var index = str.indexOf("o");index > 0; index = str.indexOf("o", index+1)){
    console.log(index);
    }
    

    See Demo

    【讨论】:

    • 这看起来很棒!谢谢迪内什卡尼!我没有对你投反对票。
    • 它正在经历无限的迭代。
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多