Here is an example of a Caesar Cipher implementation in JavaScript:

function CaesarCipher(str, shift) {
    var result = "";
    for (var i = 0; i < str.length; i++) {
        var char = str[i];
        var charCode = str.charCodeAt(i);
        if (charCode >= 65 && charCode <= 90) {
            result += String.fromCharCode((charCode - 65 + shift) % 26 + 65);
        } else if (charCode >= 97 && charCode <= 122) {
            result += String.fromCharCode((charCode - 97 + shift) % 26 + 97);
        } else {
            result += char;
        }
    }
    return result;
}

This function takes two parameters: a string and a shift value. The string is the text that you want to encrypt, and the shift value is the number of positions that each letter should be shifted by. The function uses a for loop to iterate through each character in the string, and then uses the charCodeAt() method to get the Unicode value of the character. Depending on whether the character is uppercase or lowercase, the function uses the modulus operator to shift the character’s position by the shift value.

You can use this function to encrypt a string like this:

var encrypted = CaesarCipher("HELLO WORLD", 3);
console.log(encrypted);

This will output “KHOOR ZRUOG”.

You can also create another function like this to decrypt the message

function DecryptCaesarCipher(str, shift) {
    return CaesarCipher(str, 26 - shift);
}

You can use this function to decrypt a string like this:

var decrypted = DecryptCaesarCipher("KHOOR ZRUOG", 3);
console.log(decrypted);

This will output “HELLO WORLD”

Also Read:

Categorized in: