循环遍历字符串以查找多个索引

时间:2013-06-03 13:22:17

标签: javascript jquery loops indexing indexof

我试图找出循环字符串并找到某个字母的所有索引的最有效方法。

我使用$word_or_phrase.indexOf( $letter );来查找字母的单个索引,但该字母多次出现$word_or_phrase。最有效的方法是在.indexOf返回-1之前构建所有索引的数组吗?或者您如何建议我找到所有索引?

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

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

提前感谢您的建议!

5 个答案:

答案 0 :(得分:5)

作为您发布的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"));

DEMO: 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"));

DEMO: 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"));

DEMO: http://jsfiddle.net/KfJ9H/

答案 1 :(得分: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);

答案 2 :(得分:1)

检查一下......

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;
}

答案 3 :(得分:0)

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

答案 4 :(得分:0)

试试这个

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

See Demo