Caesar Cipher and ROT13 Text Shifting
Shift ASCII letters by any integer offset with alphabet wrapping, and expose ROT13 as a fixed thirteen-position special case.
Code
function shiftLetters(text, offset) {
if (typeof text !== "string") throw new TypeError("text must be a string");
if (!Number.isInteger(offset)) throw new TypeError("offset must be an integer");
const normalized = ((offset % 26) + 26) % 26;
return text.replace(/[a-z]/gi, (char) => {
const base = char <= "Z" ? 65 : 97;
return String.fromCharCode(((char.charCodeAt(0) - base + normalized) % 26) + base);
});
}
export function caesarCipher(text, offset) {
return shiftLetters(text, offset);
}
export function rot13(text) {
return shiftLetters(text, 13);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.