JSFiddle - React, Tailwind, and code Playground
by Diana Lemen
JavaScript
function caesarCipher(s, k) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let koef = k;
if(k > alphabet.length) {
const diff = Math.floor(k/alphabet.length);
koef = k - alphabet.length * diff;
}
const begin = alphabet.substring(0, koef);
const end = alphabet.substring(koef);
const rotatedAlphabetStr = end + begin;
const arr = s.split('');
const rotatedAlphabetArr = rotatedAlphabetStr.split('');
let res = '';
const isUpperCase = (string) => /^[A-Z]*$/.test(string)
for(let i = 0; i < arr.length; i++) {
if(arr[i].match("[a-zA-Z]+")) {
const index = alphabet.split('').findIndex(item => item === arr[i].toLowerCase());
if(isUpperCase(arr[i])) {
}
res = res + (isUpperCase(arr[i]) ? rotatedAlphabetArr[index].toUpperCase() : rotatedAlphabetArr[index]);
} else {
res = res + arr[i];
}
}
return res;
}
console.log(caesarCipher('www.abc.xy', 87))