Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Encrypting a string using Caesar Cipher in JavaScript
The Caesar Cipher algorithm is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet.
For example: With a left shift of 3, D would be replaced by A, E would become B, and so on. We need to write a JavaScript function that takes in a string to be encrypted as the first argument and a shift amount as the second argument.
The shift amount can be a positive or negative integer (a positive shift signifies a shift to right whereas negative to left).
How Caesar Cipher Works
Implementation
Here's a complete implementation of the Caesar Cipher encryption function:
const str = 'thisIsAString';
const getMap = (legend, shift) => {
return legend.reduce((charsMap, currentChar, charIndex) => {
const copy = { ...charsMap };
let ind = (charIndex + shift) % legend.length;
if (ind < 0) {
ind += legend.length;
}
copy[currentChar] = legend[ind];
return copy;
}, {});
};
const encrypt = (str, shift = 0) => {
const legend = 'abcdefghijklmnopqrstuvwxyz'.split('');
const map = getMap(legend, shift);
return str
.toLowerCase()
.split('')
.map(char => map[char] || char)
.join('');
};
console.log(encrypt(str, 6));
znoyoygyzxotm
Step-by-Step Example
Let's trace through how "hello" gets encrypted with a shift of 3:
const testString = 'hello';
const shift = 3;
console.log('Original string:', testString);
console.log('Shift amount:', shift);
console.log('Encrypted result:', encrypt(testString, shift));
// Breaking it down letter by letter
const legend = 'abcdefghijklmnopqrstuvwxyz'.split('');
const map = getMap(legend, shift);
testString.split('').forEach(char => {
console.log(`${char} -> ${map[char]}`);
});
Original string: hello Shift amount: 3 Encrypted result: khoor h -> k e -> h l -> o l -> o o -> r
How It Works
The algorithm works in three main steps:
-
Create Character Map: The
getMapfunction creates a mapping object where each letter maps to its shifted equivalent - Handle Wraparound: When the shift goes beyond 'z', it wraps around to 'a' using the modulo operator
- Transform String: Each character in the input string is replaced using the mapping, preserving non-alphabetic characters
Testing Different Shifts
const message = 'javascript';
console.log('Original:', message);
console.log('Shift +5:', encrypt(message, 5));
console.log('Shift -3:', encrypt(message, -3));
console.log('Shift +13 (ROT13):', encrypt(message, 13));
Original: javascript Shift +5: ofafxhwnuy Shift -3: gfqfphpfoy Shift +13 (ROT13): wninfpevcg
Conclusion
The Caesar Cipher provides a simple introduction to encryption concepts. This JavaScript implementation handles both positive and negative shifts, automatically wraps around the alphabet, and preserves non-alphabetic characters unchanged.
