Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoderByte Letter Changes Java Script

Tags:

javascript

The question is :

Using the JavaScript, 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.

function LetterChanges(str){ 
  var result = "";
  for(var i = 0; i < str.length; i++) {
    var letters = str[i];
    if (letters == "a"|| letters == "e"|| letters == "i"|| letters == "o"|| letters =="u") {
      letters = letters.toUpperCase();
      result+=letters;
    } else if (letters == "z") {
      letters = "a";
    } else {
      var answer = "";
      var realanswer="";
      for (var i =0;i<str.length;i++) {
        answer += (String.fromCharCode(str.charCodeAt(i)+1));
      }              
      realanswer += answer
    }
  }
  return realanswer;
  return result;
}
LetterChanges();

basically, if return realanswer is placed before return result and LetterChanges is called with "o" i get the output undefined. But if it is called with a non vowel such as "b" it will output "c" which is correct.

now if i place return result before return realanswer it will work properly for vowels but not for other letters. thanks for the help

like image 862
nkr15 Avatar asked Dec 01 '25 00:12

nkr15


1 Answers

    function LetterChanges(str) { 

      return str
        .replace(/[a-zA-Z]/g, (x) =>  String.fromCharCode(x.charCodeAt(0)+1))
        .replace(/[aeiou]/g, (v) => v.toUpperCase());
    }
  1. The first part modifies the consonants by an increment of 1.

    • Regex is isolating the characters with [] versus no brackets at all. g ensures that the regex is applied anywhere in the string, as opposed to not putting g which gives you the first occurrence of the search.

    • You have to convert the characters in the string to their Unicode because incrementing is a math operation. x.charCodeAt(0) is saying at the index of 0 of the string in the argument. The increment of 1 is not within the parentheses but outside.

  2. The second part modifies the vowels to upper case.

    • This is pretty straightforward, the regex only finds the individual characters because [] are used, g for anywhere in the string. and the modifier is to make the characters become upper case.
like image 91
Cronwel Avatar answered Dec 02 '25 12:12

Cronwel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!