caesar cipher encryption javascript code example

Example 1: cesar ciupher js

function caesarCipher(str, shift) {
  const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split("");
  let res = "";

  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    const idx = alphabetArr.indexOf(char);

    // if it is not a letter, don`t shift it
    if (idx === -1) {
      res += char;
      continue;
    }

    // only 26 letters in alphabet, if > 26 it wraps around
    const encodedIdx = (idx + shift) % 26;
    res += alphabetArr[encodedIdx];
  }
  return res;
}

Example 2: Caesars Cipher javascript

var myCipher = [];
      var myArray = []; 
      
      for (i=0; i < str.length; i++) {
        // convert character - or don't if it's a punctuation mark.  Ignore spaces.
        if (str.charCodeAt(i) > 64 && str.charCodeAt(i) < 78) {
             myArray.push(String.fromCharCode(str.charCodeAt(i) + 13));
         } else if (str.charCodeAt(i) > 77 && str.charCodeAt(i) < 91) { 
             myArray.push(String.fromCharCode(77 - (90 - str.charCodeAt(i))));
         } else if (str.charCodeAt(i) > 32 && str.charCodeAt(i) < 65) {
             myArray.push(str.charAt(i));
         }
       
        // push word onto array when encountering a space or reaching the end of the string
        
        if (str.charCodeAt(i) == 32) {
          myCipher.push(myArray.join(''));
          myArray.length = 0;      
        }
        
        if (i == (str.length - 1)) {
           myCipher.push(myArray.join(''));
        }

      }

      return myCipher.join(" ");
      
    }