加密字符串JavaScript
我们需要编写一个JavaScript函数,该函数将字符串作为第一个参数,将数字作为第二个参数。
函数应通过将字符串上移给定数字来替换字符串中的每个字母表。
移位应回绕到字母的开头或结尾,就像a应该跟随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
热门推荐
4 敏字的祝福语简短
10 给红包祝福语简短搞笑
11 女儿婚礼女婿祝福语简短
12 小红书生日祝福语简短
13 送花祝福语简短十一朵
14 考试祝福语简短给对象
15 新婚抖音祝福语简短
16 新年发给客户祝福语简短
17 送离别同事简短祝福语
18 五二零朋友祝福语大全简短