Caesars Cipher - need help!

I’m getting correct results for all the criteria in this challenge, but still they are not turning green and I cannot go to the next challenge.

This is the code I wrote:

var arr1=[];
var arr2=[];
var decoded="";

function rot13(str) { 
  
  str=str.toUpperCase();
  str="\""+str+"\"";
  
  arr=str.split("");
    
  for(var i=0; i<arr.length; i++){
  
  if (str.charCodeAt(i)>=78){
    arr1.push(str.charCodeAt(i)-13);
  }
    else if(str.charCodeAt(i)<65 || str.charCodeAt(i)>90){
      
      arr1.push(str.charCodeAt(i));

    }
                else if (str.charCodeAt(i)<78){
        
        arr1.push(str.charCodeAt(i)+13);
      }
    
  }
  for(var j=0; j<arr.length; j++){

     decoded = decoded + String.fromCharCode(arr1[j]);
  }
  
  return decoded;

}

rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");

Thanks

EDIT: I didn’t check the actual code in the function, once it’s fixed as described in the other answers, you’ll still have this problem:

You have global variables: var arr1=[] and var decoded=""; (there is arr2 as well, but you aren’t using it it would seem).

  • The first time the tests run [as long as the code inside the function is fine, which you’re saying it is] you should get the correct answer. arr1 will have characters pushed into it, and decoded will contain the first answer.
  • Then the second test will run, and more characters will be pushed into arr1, and the second answer will be added to decoded.
  • Then the third test will run, and more characters will be pushed into arr1, and the third answer will be added to decoded.
  • And so on.

arr1 and decoded will get larger and larger every test, and each test after the first will fail because they will contain everything that existed prior to the current test.

Move the variables inside the function, that will scope them - they will be assigned every time the function is run, which is what you want. This is an illustration of why global variables tend to be a bad idea, so just be careful about using them in future - you normally don’t want globals, as they tend to be difficult to manage.

str="""+str+""";

Just remove that line and you will pass it, and one more thing,
same quotes can’t be use in the same one , you need to escape them as below:

str="\""+str+"\"";
// or use single ones like:
str='"' + str + '"';

I think you are confused with there example test actually they represent string within quotes, it just shows that it should be a string not string within a quote.

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

Can’t believe it was this…trying to figure it out since a couple of days :sweat_smile: