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
3 Answers
Reset to default 7To 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
版权声明:本文标题:Get indexOf char inside a string javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744518729a2610325.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论