循环遍历字符串以查找多个索引 [英] Looping Through String To Find Multiple Indexes
问题描述
我试图找出循环字符串并查找某个字母的所有索引的最有效方法。
I am trying to figure out the most efficient way of looping through a string and finding all indexes of a certain letter.
我使用过 $ word_or_phrase.indexOf($ letter);
查找单个索引的字母,但该字母多次在 $ word_or_phrase
中。最有效的方法是构建所有索引的数组,直到 .indexOf
返回-1?或者您如何建议我找到所有索引?
I have used $word_or_phrase.indexOf( $letter );
to find a single index of a letter, but the letter is in $word_or_phrase
multiple times. Would the most efficient way to do this be to build an array of all the indexes until .indexOf
returns -1? Or how would you suggest me finding all the the indexes?
我已经花时间找到了这个:
Javascript str.search()多个实例
I have already taken time and found this: Javascript str.search() multiple instances
这样可行,但对我来说,处理2个以上的效果似乎并不高效索引。如果我有10个怎么办?
This works, but to me doesn't seem efficient when dealing with more than 2 indexes. What if I had 10?
提前感谢您的建议!
推荐答案
可能是一个解决方案:
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);
这篇关于循环遍历字符串以查找多个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!