LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 6

Caesar cipher encrypt and decrypt in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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
main.js
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));

Output Verified by running it on Node.js

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links