admin管理员组

文章数量:1435859

How can I check the index of a char within a string?

var str = 'alabama';
alert(str.indexOf('a'));

The "indexOf" method seems to work only at the first occurrence of the char. Any ideas?

How can I check the index of a char within a string?

var str = 'alabama';
alert(str.indexOf('a'));

The "indexOf" method seems to work only at the first occurrence of the char. Any ideas?

Share Improve this question asked May 8, 2012 at 17:15 darksoulsongdarksoulsong 15.4k14 gold badges51 silver badges96 bronze badges 3
  • What are you trying to do? Find all occurrences of 'a'? Count how many 'a's? – arb Commented May 8, 2012 at 17:17
  • I´m trying to get the indexes of the 'a's. In fact, I need to learn the process so I can use it to identify the position of the char and wrap it with a div. – darksoulsong Commented May 8, 2012 at 17:46
  • If you have to wrap it with a div why don't you use str.replace(/a/g, "<div>a</div>"); ? – user1150525 Commented May 8, 2012 at 17:48
Add a ment  | 

3 Answers 3

Reset to default 7

To find subsequent occurrences, you need to supply the second parameter to .indexOf, repeatedly starting from one higher than the last occurrence found.

String.prototype.allIndexesOf = function(c, n) {
    var indexes = [];
    n = n || 0;
    while ((n = this.indexOf(c, n)) >= 0) {
        indexes.push(n++);
    }
    return indexes;
}

Test:

> "alabama".allIndexesOf("a")
[0, 2, 4, 6]

EDIT function updated to allow specification of a fromIndex, per String.indexOf.

You can write your own function:

function charIndexes(string, char) {
    var i, j, indexes = []; for(i=0,j=string.length;i<j;++i) {
        if(string.charAt(i) === char) {
            indexes.push(i);
        }
    }

    return indexes;
}
var str = 'alabama',i=0, ci=[];

while((i=str.indexOf('a',i))!=-1)  ci.push(i++);

alert(ci.join(', '));

本文标签: Get indexOf char inside a string javascriptStack Overflow