Skip to content

Instantly share code, notes, and snippets.

@mogelbrod
Created October 4, 2016 19:56
Show Gist options
  • Save mogelbrod/45115b8b590b04d9784f159f17e37953 to your computer and use it in GitHub Desktop.
Save mogelbrod/45115b8b590b04d9784f159f17e37953 to your computer and use it in GitHub Desktop.
Caesar cipher in JavaScript (ES6)
/**
* Applies a Caesar shift to all alphabetical characters in a string.
* Characters are converted to uppercase in the returned string.
* @param {int} key - Positions to shift (0-25).
* @param {string} str - The string to shift.
* @return {string} The shifted string.
*/
function caesarShift(str, key) {
return str.toUpperCase().replace(/[A-Z]/g, c => String.fromCharCode((c.charCodeAt(0)-65+key)%26+65))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment