javascriptcaesar-cipher

Caesar Cipher in Javascript


I am trying to write a program to solve the following problem in javascript (Written below this paragraph). I don't know why my code isn't working. Could someone help me? I'm new to javascript; this is a free code camp question.

"A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.

Write a function which takes a ROT13 encoded string as input and returns a decoded string."

function rot13(str) { // LBH QVQ VG!
  
  var string = "";
  for(var i = 0; i < str.length; i++) {
    var temp = str.charAt(i);
    if(temp !== " " || temp!== "!" || temp!== "?") {
       string += String.fromCharCode(13 + String.prototype.charCodeAt(temp));
    } else {
      string += temp;
    }
  }
  
  return string;
}

// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC")); //should decode to "FREE CODE CAMP"


Solution

  • I have tried to make it simple and I earned FREE PIZZA!. Check my solution for this.

        function rot13(str) {
        
        var alphabets =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'," ", "-", "_", ".", "&","?", "!", "@", "#", "/"];
        
        var alphabets13 = ['N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','B','C','D','E','F','G','H','I','J','K','L','M', " ", "-", "_", ".", "&","?", "!", "@", "#", "/"];
        
        var resultStr = [];
        for(let i=0; i<str.length; i++){
            for(let j =0; j<alphabets.length; j++){
                if(str[i] === alphabets[j]){
                resultStr.push(alphabets13[j]);
                }
            }
        }
        return resultStr.join("");
      };
    
      rot13("SERR CVMMN!");