Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement