create a caesar cipher function in javascript

You can create a Caesar Cipher function in JavaScript using the following code:

index.tsx
function caesarCipher(str, num) {
  num = num % 26; // ensuring the rotation is within the range of 26
  
  var lowerCaseStr = str.toLowerCase();
  var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
  var newStr = '';
  
  for(var i = 0; i < lowerCaseStr.length; i++) {
    var currentLetter = lowerCaseStr[i];
    if(currentLetter === ' ') {
      newStr += currentLetter;
      continue;
    }
    
    var currentIndex = alphabet.indexOf(currentLetter);
    var newIndex = currentIndex + num;
    
    if(newIndex > 25) newIndex = newIndex - 26;
    if(newIndex < 0) newIndex = 26 + newIndex;
    
    if(str[i] === str[i].toUpperCase()) {
      newStr += alphabet[newIndex].toUpperCase();
    } else {
      newStr += alphabet[newIndex];
    }
  }
  
  return newStr;
}

// Example usage
var encrypted = caesarCipher('hello world', 4);
console.log(encrypted); // Outputs: lipps asvph

var decrypted = caesarCipher(encrypted, -4);
console.log(decrypted); // Outputs: hello world
986 chars
37 lines

In this implementation, the caesarCipher function takes two arguments: the str (string) that you want to encrypt/decrypt, and the num (number) that represents the rotation (how many positions to shift each letter).

The function converts the string to lowercase, splits the alphabet into an array, and then loops through each letter of the input string. It handles both lowercase and uppercase letters, ignores spaces, and wraps around the alphabet if needed.

To encrypt a string, call the function with a positive num value. To decrypt the encrypted string, call the function with the negative of the original num value.

related categories

gistlibby LogSnag