Caesars Cipher, please help me figure out what is wrong with my code

Tell us what’s happening:

I am not getting the required output. Can some one please tell me what is wrong with my code?

Your code so far


function rot13(str) { // LBH QVQ VG!
  var reg = /[A-Z]/g ;
  var arr=str.split("");
  for (var i=0;i<arr.length;i++){
      if(reg.test(arr[i])) {
             arr[i]=String.fromCharCode((arr[i].charCodeAt(0) % 26) + 65);
      }
  }
  return arr.join('');
}

// Change the inputs below to test
rot13("SERR CVMMN!");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36.

Link to the challenge:

.charCodeAt() will give you the char code (i.e. 65 for A), not the position in alphabet.

Don’t use the g flag when you use test(), it has a special behaviour that you need to learn about before using it. (You May want to read about how it works so next time you know). Well, actually, don’t use a flag unnecessarily… in this case you are testing one single character, using the global flag is not necessary whatever method you use.

Thanks a lot!! Itz working now… :slight_smile: