Caesar's Cipher -- how to make my code work?

Caesar's Cipher -- how to make my code work?


Hi guys,

So I came up with a lengthy solution to the Caesar’s Cipher challenge.

I’m aware the are better solutions, but I’m just trying to see if I can tweak it to make it work.

The main problem appears to be with the whitespace in the array. I’m not sure how to join “anotherArray” while also preserving the whitespace. Maybe it’s easier to “alert()” the last code rather than “return” to see it in action.

Thanks in advance!!

function rot13(str) { // LBH QVQ VG!
  var splitStr = str.split("");
  var newArray = [];
  var anotherArray = [];
  for(i = 0; i < splitStr.length; i++){
    if(splitStr[i].charCodeAt() === 32) {
	    newArray.push(" ");
    } else if (splitStr[i].charCodeAt() >= 78 && splitStr[i].charCodeAt() <= 90 ) {
			newArray.push(splitStr[i].charCodeAt() - 13);
    } else if(splitStr[i].charCodeAt()  <= 77 && splitStr[i].charCodeAt() >= 65) {
      newArray.push(splitStr[i].charCodeAt() + 13);
	return anotherArray.join("");

// Change the inputs below to test


It is not just spaces that are causing you trouble, but even if you only had to worry about dealing with letters and spaces, the following code is not helping you at all. Why? Because instead of pushing an ASCII code into newArray, you are pushing a string character. This will be a problem when you attempt to using the String.fromCharCode function later in the code.

    if(splitStr[i].charCodeAt() === 32) {
	    newArray.push(" ");

Instead of checking for spaces and other characters that could be present in str, I think your 2nd else if could simply be an if statement and leave the other else if as is. Then, you can use an else code block to push the current character’s ASCII. This will work, because you have already made sure letters have been dealt with in the preceeding if and else if statements.


wow!! this worked after pushing the actual value rather than an empty string. And I changed the condition as well to check if “charCodeAt()” is below 65 or greater than 90.

Thanks so much for the explanation!

edit: I reworked the if statement, so that the above < 65 and > 90 falls under the “else” condition. Thank you