Caesars Cipher Need Help

Caesars Cipher Need Help
0

#1

Tell us what’s happening:

function rot13(str) { // LBH QVQ VG!
  //A-Z:65-90
  var strs = "";
  for(var a = 0; a < str.length; a++) {
    if(str.charCodeAt(a) < 65 || str.charCodeAt(a) > 90) {
      strs += str.substr(a, 1);
    }
    else {
      if(str.charCodeAt(a) + 13 > 90) {        
        var s1 = str.charCodeAt(a) + 13 - 26;
        strs += str.fromCharCode(s1);
      }
      else {
        var s2 = str.charCodeAt(a) + 13;
        strs += str.fromCharCode(s2);
      }
    }
  }
  return strs;
}

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

And the output is “TypeError: str.fromCharCode is not a function”.
What is the “TypeError: str.fromCharCode is not a function” ?


#2

Your code :

str.fromCharCode(12);

the syntax for fromCharCode() method is

String.fromCharCode(n1, n2, ..., nX)

String in syntax doesn’t mean you can replace it with any string, that’s part of syntax
they don’t accept any string variable, they only accept integer variable inside their bracket


#3

Thank you for your reply,and I forget to update my code.
So the “String.fromCharCode” does not accept variable argument ?
For example:

var s1 = str.charCodeAt(a) + 13 - 26;
str[a] = str.fromCharCode(s1);

#4

Thank you very much !!
This problem is solved.:grinning:
And here is my code:

  //A-Z:65-90
  var strs = "";
  for(var a = 0; a < str.length; a++) {
    if(str.charCodeAt(a) < 65 || str.charCodeAt(a) > 90) {
      strs += str[a];
    }
    else {
      if(str.charCodeAt(a) >= 78) {                
        strs += String.fromCharCode(str.charCodeAt(a) - 13);
      }
      else {        
        strs += String.fromCharCode(str.charCodeAt(a) + 13);
      }
    }
  }
  return strs;
}

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