Caesar Cipher - A Simple Encryption Technique

Implementing the Caesar Cipher in JavaScript

The Caesar Cipher is one of the simplest encryption techniques, where each letter is shifted a fixed number of places in the alphabet.

How It Works

The encryption process involves shifting letters based on a given key. The shift wraps around the alphabet to ensure continuous encoding.

Code Implementation


function caesarCipher(str, shift) {
    return str.split('').map(char => {
        let code = char.charCodeAt(0);
        if (char.match(/[a-z]/i)) {
            let base = char >= 'a' ? 97 : 65;
            return String.fromCharCode(((code - base + shift) % 26 + 26) % 26 + base);
        }
        return char;
    }).join('');
}
            

Challenges & Improvements

Handling non-alphabetic characters was a challenge, but the function preserves them. Future improvements could include number shifting or a more advanced cipher.