Ayo Ayo - 15 days ago 5
Javascript Question

Coderbyte Letter Changes - wrong changes

I was solving the Letter Changes challenge on Coderbyte which goes as follows:


Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm.

Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a).

Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.


But I don't know why the portion of my code that changes the letters with the next one in the alphabet doesn't work correctly. Here's the code:

function LetterChanges(str){
for(var i in str){
if(str.charAt(i).match(/[a-y]/i))
str = str.replace(str.charAt(i),String.fromCharCode(str.charCodeAt(i) + 1));
else if(str.charAt(i).match(/z/i))
str = str.replace(str.charAt(i),"a");
}
// the code to capitalize vowels follows
return str;
}
LetterChanges("Argument goes here") //outputs "Btivpfnu hofs hfsf" instead of "Bshvnfou hpft ifsf"

Answer

So, I've figured out why your code is causing you problems - took me a while to work out what was going on tho :)

This is your problem line:

str = str.replace(str.charAt(i), String.fromCharCode(str.charCodeAt(i) + 1));

In the console you can see what's happening if you log the output of str after that replace.

At first everything goes well:

Brgument goes herez
Bsgument goes herez
Bshument goes herez
Bshvment goes herez
Bshvnent goes herez
Bshvnfnt goes herez
Bshvofnt goes herez
Bshvofnu goes herez
Bshvofnu hoes herez
Bshvpfnu hoes herez
Bshvpfnu hofs herez

Until you get to here.

Bthvpfnu hofs herez

What's happening is that when it tries to change the "s" at the end of "goes" str.charAt(i) is equal to "s", but the replace simply does what it's meant to do: change the first "s" in str to a t, which is also why it doesn't change that second "s" to a "t".

Btivpfnu hofs herez
...

Everyone here has given you an answer to how you can recode, but this is specifically why your code doesn't work. Hope that helps.


Not specifically an answer to your question, but an alternative way of solving the problem:

function letterChanges(str) {

  // put the string into lowercase (not sure if you need to do this
  // but it makes sense if you only want the vowels in uppercase
  // and then split the string into an array and use `map` to...
  return str.toLowerCase().split('').map(function (el, i) {

    // swap the letters
    var swap = el !== 'z' ? String.fromCharCode(el.charCodeAt(0) + 1) : 'a';

    // and then return the letter, changing it to uppercase if it's
    // a vowel. Finally return the joined array
    return /[aeiou]/g.test(swap) ? swap.toUpperCase() : swap;
  }).join('');
}

letterChanges('Andz'); // bOEA

DEMO