@Christonja/

Caesars Cipher

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* JavaScript Algorithms and Data Structures Projects: Caesars Cipher: 
Challenge designed by FreeCodeCamp, solution derived completely from my learning obtained thanks to FreeCodeCamp and other sources on the internet, notably W3Schools.com, function calls provided by FreeCodeCamp as ways to test the algorithm */

function rot13(str) {
  var regex = /[A-Z]/;
  var newStr = "";
  var char;
  //Cycle through the original string
  for (var i = 0; i < str.length; i++) {
    //If the string matches the regular expression ie. if element of the string is an uppercase letter
    if (regex.test(str[i])) {
      //get the char code
      char = str.charCodeAt(i);
      //if the cipher is going to produce a number greater than the ascii for 'Z' then start back at the ascii for 'A'
      if ((char + 13) > 90) { char-=26; }
      //perform the cipher and place it at the end of a new string
      newStr += String.fromCharCode(char + 13);
      //if the string element failed the regex test, that means it isn't an uppercase letter and should remain where it is
    } else {
      newStr += str[i];
    }
  }
  //visual of the function calls to the console
  console.log(str + ": " + newStr);

  return newStr;
}

rot13("SERR PBQR PNZC") //should decode to FREE CODE CAMP
rot13("SERR CVMMN!") //should decode to FREE PIZZA!
rot13("SERR YBIR?") //should decode to FREE LOVE?
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") //THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
Native Browser JavaScript