Skip to content

Instantly share code, notes, and snippets.

@xullnn

xullnn/rot13.js

Created May 5, 2019
Embed
What would you like to do?
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