Encrypt text with a Caesar shift in JavaScript
Advanced · 4 min read
The Caesar cipher is one of the oldest secret codes: move every letter a fixed number of places along the alphabet. With a shift of 3, a becomes d, b becomes e, and x wraps round to a. It is far too easy to break for real secrets, but it is a perfect exercise for learning how letters and numbers relate in JavaScript, and a wrap-around trick you will use for clocks, carousels and calendars.
In this tutorial you will write caesar(text, shift). It keeps capitals as capitals, leaves punctuation alone and works with negative shifts, so decoding is just the same function with the opposite shift. You should know replace with a regex and what a function looks like. Character codes and the % operator are explained below.
Letters are numbers
Every character has a number. 'a'.charCodeAt(0) is 97, 'b' is 98, up to 'z' at 122. Capitals run from 'A' at 65 to 'Z' at 90. String.fromCharCode(100) goes the other way and gives 'd'.
So shifting a letter is arithmetic: turn it into a number, add the shift, turn it back.
Wrapping round with %
a % b is the remainder after dividing a by b. Counting letters from 0 (a is 0, z is 25), position 23 plus 3 is 26, and 26 % 26 is 0, which is a. The remainder keeps every result between 0 and 25.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
56 Caesar cipher
hardShift every letter along the alphabet by n places, wrapping round at the end, and leave everything else alone. Decoding must be the same function with the opposite shift.
Stuck? Three hints, smallest first
- 1. Work from the code of
aorA, so the case is preserved. - 2. Wrap with the remainder operator, but remember it can return a negative number.
- 3.
((x % 26) + 26) % 26is the version that handles a negative shift.
Step 1: shift one lowercase letter
const code = 'x'.charCodeAt(0);
console.log(code); // 120
const position = code - 97; // 23: x is the 24th letter, counting from 0
const moved = (position + 3) % 26;
console.log(moved); // 0
console.log(String.fromCharCode(97 + moved)); // 'a'
Subtracting 97 turns a to z into 0 to 25. After adding the shift and wrapping, adding 97 back turns the position into a letter code again. x shifted by 3 wraps to a.
Step 2: keep the case
Capitals start at 65, not 97. Pick the right starting point, called the base, for each letter:
const base = (c) => (c.charCodeAt(0) < 97 ? 65 : 97);
console.log(base('H')); // 65
console.log(base('h')); // 97
Every capital has a code under 97 and every lowercase letter is 97 or above, so one comparison tells them apart. Shifting relative to the base keeps a capital a capital.
Step 3: only touch letters
function caesar(text, shift) {
return text.replace(/[a-zA-Z]/g, (c) => {
const code = c.charCodeAt(0);
const base = code < 97 ? 65 : 97;
const moved = (code - base + shift) % 26;
return String.fromCharCode(base + moved);
});
}
console.log(caesar('abc', 3)); // 'def'
console.log(caesar('xyz', 3)); // 'abc'
console.log(caesar('Hello, World!', 3)); // 'Khoor, Zruog!'
replace with /[a-zA-Z]/g calls our function once for every letter and swaps in what it returns. Spaces, commas and ! don't match, so they stay exactly as they were.
Step 4: a negative shift, the natural wrong turn
To decode, shift backwards. Try -1 on 'abc'; you want 'zab':
console.log(-1 % 26); // -1
function caesar(text, shift) {
return text.replace(/[a-zA-Z]/g, (c) => {
const code = c.charCodeAt(0);
const base = code < 97 ? 65 : 97;
const moved = (code - base + shift) % 26;
return String.fromCharCode(base + moved);
});
}
console.log(caesar('abc', -1)); // '`ab'
In JavaScript, % keeps the sign of the number on its left, so -1 % 26 is -1, not 25. Then 97 + -1 is 96, the code for a backtick. Instead of z you get punctuation.
Step 5: the fix
console.log(((-1 % 26) + 26) % 26); // 25
console.log(((29 % 26) + 26) % 26); // 3
Add 26 after the first remainder, then take the remainder again. A negative result becomes positive, and a positive one is brought back into 0 to 25 by the second %. ((x % 26) + 26) % 26 is the line worth remembering for any wrap-around.
Step 6: the finished cipher
function caesar(text, shift) {
return text.replace(/[a-zA-Z]/g, (c) => {
const code = c.charCodeAt(0);
const base = code < 97 ? 65 : 97;
const moved = (((code - base + shift) % 26) + 26) % 26;
return String.fromCharCode(base + moved);
});
}
console.log(caesar('abc', -1)); // 'zab'
console.log(caesar('abc', 26)); // 'abc'
console.log(caesar(caesar('Lagos 2025', 7), -7)); // 'Lagos 2025'
console.log(caesar(caesar('Lagos', 13), 13)); // 'Lagos'
console.log(caesar('café', 1)); // 'dbgé'
Shifting by 26 goes all the way round, so nothing changes. Encoding with 7 and decoding with -7 gives back the original. A shift of 13, called ROT13, undoes itself because 13 + 13 is 26. And é isn't in [a-zA-Z], so it passes through untouched.
Is it secure?
No. There are only 25 useful shifts, so anyone can try them all in seconds. Counting which letters appear most also gives the shift away quickly. Use it for puzzles and learning, never for real secrets.
The full solution
The panel has caesar and prints a forward shift, a wrap, a sentence, a negative shift and ROT13 applied twice. Press Run, then read the checks underneath.
function caesar(text, shift) {
return text.replace(/[a-zA-Z]/g, (c) => {
const code = c.charCodeAt(0);
const base = code < 97 ? 65 : 97; // 'A' or 'a'
// % can return a negative number, so add 26 before taking it again.
const moved = (((code - base + shift) % 26) + 26) % 26;
return String.fromCharCode(base + moved);
});
}
console.log("caesar('abc', 3) :", caesar('abc', 3));
console.log("caesar('xyz', 3) :", caesar('xyz', 3), '<- wrapped');
console.log("caesar('Hello, World!', 3):", caesar('Hello, World!', 3));
console.log("caesar('abc', -1) :", caesar('abc', -1), '<- negative, also wrapped');
console.log('ROT13 twice returns the original:', caesar(caesar('Lagos', 13), 13));
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three places forward', caesar('abc', 3), 'def');
test('the end of the alphabet wraps round', caesar('xyz', 3), 'abc');
test('case is preserved', caesar('Hello, World!', 3), 'Khoor, Zruog!');
test('punctuation and digits are left alone', caesar('a1!', 3), 'd1!');
test('a negative shift goes backwards and wraps', caesar('abc', -1), 'zab');
test('shifting by the alphabet length changes nothing', caesar('abc', 26), 'abc');
test('and 29 is the same as 3', caesar('abc', 29), caesar('abc', 3));
test('decoding is the same function with the opposite shift', caesar(caesar('Lagos 2025', 7), -7), 'Lagos 2025');
test('ROT13 is its own inverse', caesar(caesar('Lagos', 13), 13), 'Lagos');
test('an accented letter is outside a-zA-Z, so it is not shifted', caesar('café', 1), 'dbgé');
test('the length never changes', caesar('Hello, World!', 5).length, 'Hello, World!'.length);
((x % 26) + 26) % 26 is the line worth copying. JavaScript's % keeps the sign of the left operand, so -1 % 26 is -1, not 25. Without the correction a negative shift produces code points below 'a' and the output turns into punctuation. It is the same fix needed for any wrap-around index.
The accent assertion is the honest limit: [a-zA-Z] is a 26-letter assumption, and every character outside it passes through untouched. That is correct behaviour for a cipher defined over the English alphabet, and it is worth stating rather than discovering.
A Caesar cipher is a puzzle, not security. It has 25 possible keys and yields to letter-frequency counting instantly — which is what exercise 34 was building.
Common mistakes
- Using
% 26alone with negative shifts.-1 % 26is-1. Use((x % 26) + 26) % 26. - Forgetting the base. Without subtracting 97 (or 65) first, the remainder wraps at the wrong place.
- Shifting every character. Spaces and punctuation get mangled. Match only
[a-zA-Z].
Try it yourself
- Write
decode(text, shift)in one line usingcaesar. - Print all 25 shifts of
'Khoor'and spot the one that reads as English. - Extend the cipher to shift digits too, wrapping
9round to0.