Skip to content

I try to build ROT 13 cipher in JavaScript, I did it but output not shown in console please check what’s wrong in it

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

function rot13(str) {
    let newStr="";
  let upperAlph=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","W","X","Y","Z"]
  let rotAlph=["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"];
  for(let i=0; i<str.length; i++){
 
    let letter=str[i];
    let letTest=/[A-Z]/g;
    if(letTest.test(letter)){
      let indexOfLetter=upperAlph.indexOf(letter);
      let newLetter=rotAlph[indexOfLetter];
      newStr+newLetter;
    }
    else{
      newStr+letter;
    }
  }
  return newStr;
}

console.log(rot13("SERR PBQR PNZC"));

Answer

Fixed your code, look at lines 12 and 15 I believe:

function rot13(str) {
    let newStr="";
  let upperAlph=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","W","X","Y","Z"]
  let rotAlph=["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"];
  for(let i=0; i<str.length; i++){
 
    let letter=str[i];
    let letTest=/[A-Z]/g;
    if(letTest.test(letter)){
      let indexOfLetter=upperAlph.indexOf(letter);
      let newLetter=rotAlph[indexOfLetter];
      newStr += newLetter;
    }
    else{
      newStr += letter;
    }
  }
  return newStr;
}

console.log(rot13("SERR PBQR PNZC"));

I would also use map type object instead of 2 arrays:

alphMap = {A: 'N', B: 'O', C: 'P', ..., Z: 'M'};

You can find your substitute letter like so:

let newLetter = alphMap[letter];

No need to match indexes.