Skip to content

Instantly share code, notes, and snippets.

@Christonja
Last active April 9, 2019 12:55
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 Christonja/9d789820ad6c1b7c4357935dc7024ddb to your computer and use it in GitHub Desktop.
Save Christonja/9d789820ad6c1b7c4357935dc7024ddb to your computer and use it in GitHub Desktop.
Caesars Cipher created by Christonja - https://repl.it/@Christonja/Caesars-Cipher
/* 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment