caesar cipher using 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 (idx === -1) {
res += char;
continue;
}
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++) {
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));
}
if (str.charCodeAt(i) == 32) {
myCipher.push(myArray.join(''));
myArray.length = 0;
}
if (i == (str.length - 1)) {
myCipher.push(myArray.join(''));
}
}
return myCipher.join(" ");
}