Sammy Sammy - 1 month ago 11
Javascript Question

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

how to shift each letter in the given string N places down in the alphabet? Punctuation, spaces, and capitalization should remain intact. For example if the string is "ac" and num is 2 the output should be "ce". What's wrong with my code? It converts letter to ASCII and adds given number then converts from ASCII to letter back. The last line replaces space.

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(), ' ');

}


I'm getting

TypeError: charcode.fromCharCode is not a function

Answer

You need to pass an argument to the fromCharCode method using the String object. Try:

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;

}
                               
alert(CaesarCipher('test', 2));

I had to modify the return statement, because it was introducing a bug for me

Comments