문자열을 첫 번째 인수로, 숫자를 두 번째 인수로 취하는 JavaScript 함수를 작성해야 합니다.
함수는 주어진 숫자만큼 알파벳을 위로 이동하여 문자열의 각 알파벳을 대체해야 합니다.
시프팅은 정의되지 않은 결과나 무효 결과 대신 z를 따라야 하는 것처럼 알파벳의 시작이나 끝으로 돌아가야 합니다.
예시
const str = 'this is a str';
const encryptString = (str = '', num = 1) => {
const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
str = str.toLowerCase();
let res = "";
for (let i = 0; i < str.length; i++) {
const letter = str[i];
if (alphabet.indexOf(letter) === -1) {
res += letter;
continue;
}
let index = alphabet.indexOf(letter) + num % 26;
if (index > 25){
index -= 26;
};
if (index < 0){
index += 26;
};
if(str[i] === str[i].toUpperCase()){
res += alphabet[index].toUpperCase();
}else{ res += alphabet[index];
};
}
return res;
};
console.log(encryptString(str, 4)); 출력
콘솔의 출력은 -
xlmw mw e wxv