Can't work out what's going on here... indexOf and replacing letter

I’m doing a challenge where all vowels should be changed to their place in the string.
What I came up with works on some, but not others. I have no idea what’s going on!

function vowel2index(str) {
 //code me
  str = str.split('')
  for (var n = 0; n < str.length; n++) {
    if (/[aiueoAIUEO]/g.test(str[n]) === true) {
      str[n] = str.indexOf(str[n + 1])
  return str.join('')

vowel2index('this is my string')
// should return 'th3s 6s my str15ng'
//but it returns 'th3s 3s my str15ng'

what on earth is happening for some of the vowels??
Thank you!

A few related things all tripping you up…

You are to replace the vowel with it’s place in the string - you already have it’s index, that is n. Just correct that for starting counting places at one instead of starting counting at zero.

indexOf(str[n+1]) is searching for the letter that follows the vowel. str[n] vowel, str[n+1] is letter following vowel.

indexOf() returns the index of the first instance that matches. In the case of the two “i” being changed to 3 indexOf(str[n+1]) is same as indexOf(“s”). The index of the first “s” is index 3 in both cases.

1 Like

I’m sorry but I’m not sure what you mean. If I do it without a +1 it returns the index, but I want the index plus one. Wherever I try to add the +1, it never comes up with the right numbers…

Ok, I got it by adding the +1 outside of the brackets, and outside of the square brackets, so thank you!

But I’m still a bit confused why that worked…

You know the index of any vowel found. The index is related to position (one less) so you really don’t need to use indexOf to find position at all. Avoid indexOf and the two following issues go away

This only works if the letter following the vowel is unique and if vowel is not the last letter of string.

indexOf always returns the first instance that matches. Not always what the one you want

Put this extra line in your if statement and you will see that you have the answer you need without indexOf

if (/[aiueoAIUEO]/g.test(str[n]) === true) {
      console.log("vowel found! index: " + n + " place in string: " + (n+1) )