Search code examples
javascriptcaesar-cipher

How to use String.charCodeAt(); to get and store char code values of each letter of a string at once and store them?


Here is my code for getting char code values for first letter of the string,then converting that char code value to minus 13(I need to do this in my question). Then I convert that char code to get the character.As far now I am able to do it for first or any character in the given input string.But what I want to do is to get char code for each letter in string all at once and then decrement each char code by 13,then convert each char code back to a letter and output the whole converted string.And also my input is NOT fixed,there are many test cases which keep changing.Please help me solve it keeping these points in mind.Here my code:

function rot13(str) { // LBH QVQ VG! It is just a useless comment.

var a=str.charCodeAt(0);//I am able to  get char code of 0 or any other  index but just one at a tim,how to do it for all the index values?
a-=13;//I need to decrement eaach char code by 13

var b=String.fromCharCode(a);//and from each char code I need to give back aletter but I want to return a whole converted string back as ouput not just a single converted letter.How to do it?
return b;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");

Solution

  • You need to loop across all the characters of the string, then keep on appending the changed value to string b, like this:

    function rot13(s)
     {
        return (s ? s : this).split('').map(function(_)
         {
            if (!_.match(/[A-Za-z]/)) return _;
            c = Math.floor(_.charCodeAt(0) / 97);
            k = (_.toLowerCase().charCodeAt(0) - 83) % 26 || 26;
            return String.fromCharCode(k + ((c == 0) ? 64 : 96));
         }).join('');
     }
    
    alert(rot13("SERR PBQR PNZC"));