Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 488
Sammy Avatar asked Oct 12 '15 15:10

Sammy


People also ask

How do you shift characters?

Create an array of characters from the input string. Traverse the String array from the start (index 0) to end (n-1, where n is the length of an array). Perform the shift operation on each and every character of an array. Convert modified array of characters to string and return it.

How do I use charCodeAt in JavaScript?

The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string. The index of the first character is 0, the second is 1, .... The index of the last character is string length - 1 (See Examples below). See also the charAt() method.


1 Answers

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;

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

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

like image 153
Ally Ripp Avatar answered Oct 12 '22 04:10

Ally Ripp