Skip to content

Instantly share code, notes, and snippets.

@xullnn
Created May 5, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xullnn/cca1634929bb2cc9d05443e01a83fd44 to your computer and use it in GitHub Desktop.
Save xullnn/cca1634929bb2cc9d05443e01a83fd44 to your computer and use it in GitHub Desktop.
Rot13 in Javascript
const LOWER_START = 97;
const UPPER_START = 65;
const LOWER_END = LOWER_START + 26;
const UPPER_END = UPPER_START + 26;
function newAsciiOf(char) {
var newAscii = char.charCodeAt() + 13;
if (/[a-z]/.test(char) && newAscii >= LOWER_END) {
newAscii = (LOWER_START + (newAscii % LOWER_END));
} else if (/[A-Z]/.test(char) && newAscii >= UPPER_END) {
newAscii = (UPPER_START + (newAscii % UPPER_END));
}
return newAscii;
}
function rot13(string) {
var newStr = '';
var char;
for(var i = 0; i < string.length; i += 1) {
char = string[i];
if (/[^a-zA-Z]/.test(char)) {
newStr += char;
} else {
newStr += String.fromCharCode(newAsciiOf(char));
}
}
return newStr;
}
console.log(rot13('Teachers open the door, but you must enter by yourself.'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment