Looping Through String To Find Multiple Indexes

一个人想着一个人 提交于 2019-12-04 14:15:53

Could be a solution:

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

As the answer in the StackOverflow link you posted shows, you can use the second parameter of indexOf to define where the search starts in the string. You can continue looping over the string, using this technique, to get the indexes of all matched substrings:

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/

Another option is to use a regular expression to find all matches:

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/

And yet another option is to manually loop through the string's characters and compare to the target:

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/

check this ...

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

Try like this

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

See Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!