Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. /* JavaScript Algorithms and Data Structures Projects: Caesars Cipher:
  2. Challenge designed by FreeCodeCamp, solution derived completely from my learning obtained thanks to FreeCodeCamp
  3. and other sources on the internet, notably W3Schools.com, function calls provided by FreeCodeCamp as ways to
  4. test the algorithm */
  5.  
  6. function rot13(str) {
  7. var regex = /[A-Z]/;
  8. var newStr = "";
  9. var char;
  10. //Cycle through the original string
  11. for (var i = 0; i < str.length; i++) {
  12. //If the string matches the regular expression ie. if element of the string is an uppercase letter
  13. if (regex.test(str[i])) {
  14. //get the char code
  15. char = str.charCodeAt(i);
  16. //if the cipher is going to produce a number greater than the ascii for 'Z' then start back at the ascii for 'A'
  17. if ((char + 13) > 90) { char-=26; }
  18. //perform the cipher and place it at the end of a new string
  19. newStr += String.fromCharCode(char + 13);
  20. //if the string element failed the regex test, that means it isn't an uppercase letter and should remain where it is
  21. } else {
  22. newStr += str[i];
  23. }
  24. }
  25. //visual of the function calls to the console
  26. console.log(str + ": " + newStr);
  27.  
  28. return newStr;
  29. }
  30.  
  31. rot13("SERR PBQR PNZC") //should decode to FREE CODE CAMP
  32. rot13("SERR CVMMN!") //should decode to FREE PIZZA!
  33. rot13("SERR YBIR?") //should decode to FREE LOVE?
  34. 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