-1

I am wondering how to get all the indexes of a repeating letter in a string, like:

"bananas from bahamas"

i want to get all the indexes of "a". If i do str.indexOf("a"), i will only get the first "a" that is in the string.

Every time i attempt to check the index of that letter, i get 1.

I want:

str.indexOf("a") === 1
str.indexOf("a") === 3
str.indexOf("a") === 5
str.indexOf("a") === 14
str.indexOf("a") === 16
str.indexOf("a") === 18

EDIT: I will try to refrain from using loops. is there a solution in which i can do this without loops?

thx in advance

nova_n
  • 23
  • 7
  • Have you read any [`.indexOf()` doco](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf)? The function takes an optional second argument... – nnnnnn Aug 09 '16 at 21:51
  • Using map you can do: `str.split("").map(function(ch, idx){if(ch==='a'){ indx.push(idx); }});` – DIEGO CARRASCAL Aug 09 '16 at 22:13

1 Answers1

0

You can iterate over the string and keep track of the indices yourself:

 var indices= [], 
        i;

 for(i = 0; i < str.length; i++) {
   if (str[i] === 'a') {
     indices.push(i);
   }
 }
Igor
  • 33,276
  • 14
  • 79
  • 112