Explain rot13 javascript.

323    Asked by Amitraj in Java , Asked on Oct 10, 2022

I wrote a ROT13 cipher script rotating uppercase letters only. Can this function be improved?

ROT13 Wikipedia article

function rot13(str) {
var codeA = "A".charCodeAt(0);
var codeN = "N".charCodeAt(0);
var codeZ = "Z".charCodeAt(0);
var newArr = [];
for(var i =0; i    var code = str.charCodeAt(i);
    if(code>=codeA && code<=codeZ){
        if(code>=codeN)
            newArr.push(String.fromCharCode(code-13));
        else
            newArr.push(String.fromCharCode(code+13));
    }else{
        newArr.push(str[i]);}
    }
     return newArr.join("");
}
Answered by Alison Kelly

2020 TypeScript Version:


A shift argument must be given, but you can choose 13 for rot13 javascript or any other number.

// Caesar Cipher
const caesarCipher = (string: string, shift: number) => {
  // Alphabet
  const alphabet: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  // Encoded Text
  let encodedText: string = '';
  // Adjust Shift (Over 26 Characters)
  if (shift > 26) {
    // Assign Remainder As Shift
    shift = shift &;
  }
  // Iterate Over Data
  let i: number = 0;
  while (i < string xss=removed xss=removed xss=removed xss=removed>
    // Special Characters
    else {
      // Append To String
      encodedText += string[i];
    }
    // Increase I
    i++;
  }
  return encodedText;
};

Example #1:

console.log(caesarCipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 2));
Output:
CDEFGHIJKLMNOPQRSTUVWXYZAB
Example #2:
console.log(caesarCipher('GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.', 26 + 13)); 

Output:THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX.



Your Answer