Running the code
The quickest way is the browser: press F12, open the Console tab, paste the code and press Enter. To run it outside a browser, save it as caesar.js and use Node.js:
node caesar.jsIf the cipher itself is new to you, the guide explains it without code.
How the code works
The for...of loop reads the text one character at a time, and the regular expression picks out the letters A to Z in either case. charCodeAt(0) gives a letter’s number: 72 for H and 104 for h. Subtracting 65 or 97 gives its place in the alphabet, from 0 to 25.
After the shift is added, the modulo wraps the result around, so with a shift of 3 the letter Z lands on C. String.fromCharCode then turns the number back into a letter.
Everything else takes the else branch and stays as it is. That includes accented letters, which the regular expression doesn’t match.
Decrypting in JavaScript
You don’t need a second function. Decrypting is the same shift in the other direction, so pass a negative number:
console.log(caesar("Khoor Zruog!", -3));// Hello World!This is why the formula has the extra + 26. In JavaScript, % keeps the sign of the left number, so -3 % 26 is -3 and String.fromCharCode would return the wrong character. Adding 26 and taking the modulo again gives 23, which takes A back to X. Python’s % does this for you, as the Python version shows.
A Caesar cipher web page
This is a complete page: save it as an .html file and open it in a browser. The result updates as you type, and all the work happens on your computer.
<textarea id="text"></textarea><input id="shift" type="number" value="3"><output id="result"></output> <script> // Paste the caesar function here const text = document.querySelector("#text"); const shift = document.querySelector("#shift"); const result = document.querySelector("#result"); function update() { result.textContent = caesar(text.value, Number(shift.value)); } text.addEventListener("input", update); shift.addEventListener("input", update);</script>Two details matter here. An input’s value is always a string, so the shift goes through Number(). And the result is written with textContent, because innerHTML would run any HTML someone typed into the box.
A command-line tool in Node.js
Replace the last two lines of caesar.js with this to take the shift and the text from the command line:
const [shift, ...words] = process.argv.slice(2);console.log(caesar(words.join(" "), Number(shift))); // node caesar.js 3 Hello// KhoorBreaking the cipher with brute force
An alphabet of 26 letters leaves only 25 shifts to try, so a short loop can read a message without the key. Look through the output for the line that makes sense:
function crack(text) { for (let shift = 1; shift < 26; shift++) { console.log(shift, caesar(text, -shift)); }} crack("Khoor Zruog!");// 1 Jgnnq Yqtnf!// 2 Ifmmp Xpsme!// 3 Hello World!// ...The article on brute force attacks goes deeper, and the online solver does the same in your browser.
A shorter version with replace
replace with a global regular expression calls your function for every letter and leaves the rest alone, so you don’t need a loop or an else.
const caesar = (text, shift) => text.replace(/[a-z]/gi, (char) => { const base = char <= "Z" ? 65 : 97; const code = char.charCodeAt(0) - base; return String.fromCharCode(((code + shift) % 26 + 26) % 26 + base); });Other alphabets and digits
To shift anything beyond A to Z, keep the alphabet in a string and find each character with indexOf(). In this example the alphabet includes digits:
const ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; function caesarAlphabet(text, shift) { const size = ALPHABET.length; let result = ""; for (const char of text) { const position = ALPHABET.indexOf(char.toLowerCase()); if (position === -1) { result += char; } else { const next = ALPHABET[((position + shift) % size + size) % size]; result += char === char.toLowerCase() ? next : next.toUpperCase(); } } return result;} console.log(caesarAlphabet("Room 101", 3));// Urrp 434The wrap-around now uses the alphabet’s length, so you only have to change the string to support another language. Our Caesar cipher tool has ready alphabets for Polish, German, Spanish and French if you want to compare results.
Encrypting a text file
In Node.js, reading and writing a file takes one line each. This code uses import, so name the file caesar.mjs or set "type": "module" in package.json.
import { readFileSync, writeFileSync } from "node:fs"; const text = readFileSync("message.txt", "utf8");writeFileSync("encrypted.txt", caesar(text, 3));Using a ready library
If you need the cipher in a project and don’t want to maintain it, our caesar-cipher-js library has no dependencies and includes TypeScript types. Install it with npm install caesar-cipher-js:
import { encrypt, decrypt } from "caesar-cipher-js"; console.log(encrypt("Hello World!", 3));// Khoor Zruog!console.log(decrypt("Khoor Zruog!", 3));// Hello World!Testing your code
Node.js has an assertion module built in, so a few lines catch most bugs: wrapping past Z, keeping upper and lower case, leaving punctuation alone, and getting the original text back. If nothing is wrong, it prints OK.
import assert from "node:assert/strict"; assert.equal(caesar("ABC", 3), "DEF");assert.equal(caesar("xyz", 3), "abc");assert.equal(caesar("Hello, World!", 5), "Mjqqt, Btwqi!");assert.equal(caesar(caesar("JavaScript", 7), -7), "JavaScript");assert.equal(caesar("A", -27), "Z");assert.equal(caesar("é", 3), "é");console.log("OK");Common mistakes
The most common one is leaving the shift as a string: 7 + "3" gives "73", which silently produces the wrong letter. Next comes % with a negative shift, described above. And don’t use innerHTML to show the result, since the text comes from the user.
Frequently asked questions
Does this work in every browser?
Yes, every current browser supports the syntax used here. We ran the code on this page in Node.js 25 and tested the web page in a browser.
Can I use this to protect real data?
No. Anyone can break it in seconds with the loop shown above. Use it to learn and for puzzles. For real data, browsers and Node.js provide modern encryption through the Web Crypto API.
How can I check that my result is right?
Enter the same text and shift in our Caesar cipher tool and compare. You can also call the free REST API from your own tests.