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?
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.
String.indexOf() - the search string doesn't have to be a single character.
str.replace(/a/g, "<div>a</div>");?