Cần viết hàm JavaScript nhận chuỗi làm đối số đầu tiên và số làm đối số thứ hai. Hàm thay thế mỗi chữ cái trong chuỗi bằng cách dịch nó lên bảng chữ cái bằng số cho trước.
Việc dịch phải quay vòng trở lại đầu hoặc cuối bảng chữ cái, ví dụ a theo sau z thay vì undefined.
Ví dụ
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));
Kết quả
Kết quả trong console sẽ là:
xlmw mw e wxv