0

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?

3
  • What are you trying to do? Find all occurrences of 'a'? Count how many 'a's? 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. 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>"); ? Commented May 8, 2012 at 17:48

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

yeah, there's a bad performance overhead adding to the prototype of built-in types in Chrome - jsperf.com/indexofso/2
Note also that this version preserves the semantics of String.indexOf() - the search string doesn't have to be a single character.
that's true, but the question was just about chars. So charAt will be ok, too.
Thx, this will do just fine. o/ But I´ll use Bennika´s because I felt a little slowdown in the page using yours (I´m doing this search in a blog post. So its a really huge string).
4

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

Comments

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.