javascript - JS : how to shift each letter in the given string N places down in the alphabet?

标签 javascript string

如何将给定字符串中的每个字母在字母表中向下移动 N 位?标点符号、空格和大小写应保持不变。例如,如果字符串为“ac”且 num 为 2,则输出应为“ce”。我的代码有什么问题?它将字母转换为 ASCII 并添加给定数字,然后从 ASCII 转换为回字母。最后一行替换空格。

function CaesarCipher(str, num) {

    str = str.toLowerCase();
    var result = '';
    var charcode = 0;

    for (i = 0; i < str.length; i++) {
        charcode = (str[i].charCodeAt()) + num;
        result += (charcode).fromCharCode();
    }
    return result.replace(charcode.fromCharCode(), ' ');

}

我得到了

TypeError: charcode.fromCharCode is not a function

最佳答案

您需要使用 String 对象将参数传递给 fromCharCode 方法。尝试:

function CaesarCipher(str, num) {
    // you can comment this line
    str = str.toLowerCase();

    var result = '';
    var charcode = 0;

    for (var i = 0; i < str.length; i++) {
        charcode = (str[i].charCodeAt()) + num;
        result += String.fromCharCode(charcode);
    }
    return result;

}
console.log(CaesarCipher('test', 2));

我不得不修改返回语句,因为它给我引入了一个错误

关于javascript - JS : how to shift each letter in the given string N places down in the alphabet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084862/

相关文章:

javascript - 使用 Handsontable 在同一列中对纯文本和 html 进行排序问题

javascript - 奇怪的箭头函数参数行为

将整数转换为字符串 (C)

java - 使用 SWIG 的 Java 和 C++ 中的奇怪字符串行为

javascript - Owlcarousel2 "dots:true"不工作?

javascript - 如何使用 .load() 使用 jquery 更改图像

java - android java - 将字符串转换为字节变量

java - 检查一个字符串是否包含另一个字符串的所有字符

ios - 如何从 Objective-C 中的数组获取当前字符串值

javascript - 如何将包含按钮的 Kendo Grid 中的列的值发送到 ClientTemplate?