加密字符串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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短