Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

Change every letter in the string to the letter following it in the alphabet, so a becomes b, z becomes a, etc

So i was trying to solve this challenge in coderbyte. I understand the given answer except for the following:

String.fromCharCode(char.charCodeAt() + 1);

Where does that String come from? Where does fromCharCode gets its values from? How does it know it needs to take any value from the regExpression

/[a-z]/gi

?

Here goes the whole code:

function letterChanges(str) { 

  const converted = str.replace(/[a-z]/gi, function(char) { 
    return (char === 'z' || char === 'Z') ? 'a' : String.fromCharCode(char.charCodeAt() + 1);
  });

  const capitalized = converted.replace(/a|e|i|o|u/gi, function(vowel) { 
    return vowel.toUpperCase();
  });

  return capitalized;         
}
console.log (letterChanges("Anda a lavarte el ...alma"));   

Is there anybody out there that could please help me understand that piece of code? Thanks

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,850 Points

String is a global JS object constructor and, like other global objects, it has methods (some also have properties). One method is fromCharCode, which takes a character code (ie a number that corresponds to a character), and returns the character for that code.

Concerning code, i'll add comments to clarify:

function letterChanges(str) { 
// here str will call replace for any char that is a-z and will grab all, not just first (eg 'g' flag) and will avoid case (eg 'i' flag)
  const converted = str.replace(/[a-z]/gi, function(char) {  // the function will apply to each char
   // example: char = 'a' -> char.charCodeAt() -> returns 97 -> 97 + 1 = 98 -> String.fromCharCode(98) -> return 'b'  
    return (char === 'z' || char === 'Z') ? 'a' : String.fromCharCode(char.charCodeAt() + 1);
  });

  const capitalized = converted.replace(/a|e|i|o|u/gi, function(vowel) { 
    return vowel.toUpperCase();
  });

  return capitalized;         
}
console.log (letterChanges("Anda a lavarte el ...alma"));  
RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

Thank you so much Clayton for taking the time to help. Man i think i've just read the code with the comments for the 6th time and i think i get it now. Thanks. i need to learn object constructors