Ad space (banner)
🟨JavaScript Lessons
Lesson 35 / 69

Building a Caesar Cipher (a Letter-Shifting Cipher)

In this lesson you'll practice string manipulation using character codes by implementing the Caesar cipher, a classic type of cipher. This is for people searching "JavaScript how to implement encryption" or "character code charCodeAt usage."

The Caesar cipher is a simple cipher, dating back to ancient Rome, that replaces each letter of the alphabet by shifting it a fixed number of places. Picture it like "a secret-code game where you shift the alphabet by 3 letters when you talk." You implement it by converting characters to numbers (character codes) with .charCodeAt(), doing the calculation, then converting them back to characters with String.fromCharCode().

The sample code combines .replace() with the regular expression /[A-Z]/g to apply the shift only to uppercase English letters. The key point is that after adding shift to the character code, applying % 26 keeps the result within a range of 26 letters — this achieves the "wrap all the way around" behavior of returning to A right after Z.

Compared to modern encryption technology this is extremely simple and easy to break, but it's a great subject for practicing character-code arithmetic, a basic programming operation. A common beginner stumbling block is accidentally shifting characters other than letters (symbols or non-English characters) too, when doing this character-code arithmetic — you need to correctly narrow the target range.

As a gateway into modern cryptography, try getting hands-on with the mechanism itself. Actual security fields use far more complex mathematical structures than this kind of classical cipher, but the idea of "treating characters as numbers and computing with them" is also the foundation for learning more advanced cryptographic techniques.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)