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
//Solution with Regular expression and Array of ASCII character codes
function rot13(str) {
  //retCharArray is an Array of character codes for the solution
  var rotCharArray = [];
  //regular expression for all upper case letter from A to Z
  var regEx = /[A-Z]/ ;
  //split str into a character array
  str = str.split("");
  //iterate over each character in the array
  for (var x in str) {
    //regEx.test(str[x]) will return (true or false) if it maches the regEx or not
    if (regEx.test(str[x])) {
      // A more general approach
      // possible because of modular arithmetic 
      // and cyclic nature of rot13 transform
      rotCharArray.push((str[x].charCodeAt() - 65 + 13) % 26 + 65);
    } else {
      rotCharArray.push(str[x].charCodeAt());
    }
  }
  //make a string with character codes from an array of character codes
  str = String.fromCharCode.apply(String, rotCharArray);
  return str;
}


// Change the inputs below to test
rot13("LBH QVQ VG!");
Native Browser JavaScript