Question 6
Back to Exercise
Shift each letter by k positions (wrapping z → a), keep case, leave other characters unchanged, and show that shifting back decrypts it.
Solution
function caesar(text, k) {
const shift = ((k % 26) + 26) % 26; // also works for negative k
return text.replace(/[a-z]/gi, (ch) => {
const base = ch <= "Z" ? 65 : 97; // 'A' or 'a'
return String.fromCharCode(((ch.charCodeAt(0) - base + shift) % 26) + base);
});
}
const secret = caesar("Hello, World!", 3);
console.log(secret);
console.log(caesar(secret, -3));
console.log(caesar("xyz XYZ", 4));
Khoor, Zruog! Hello, World! bcd BCD
Each letter is mapped to 0–25, shifted, wrapped with % 26 and mapped back. ((k % 26) + 26) % 26 turns -3 into 23, so the same function decrypts.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!