user3389343
user3389343

Reputation: 63

Javascript charCodeAt() not returning correct codes.. or is it?

I'm trying to find the keycodes (if that's even what I need) and to change the character to the incremented keycode (this is just for a coding challenge) and it's not working

function LetterChanges(str) { 
var newString = "";
var keyCode;
  for(var i = 0; i < str.length; ++i)
  {

    keyCode = str.charCodeAt(i);
    console.log(keyCode);
    if( keyCode > 57 && keyCode < 122)
    {

         //add 1 to the keycode

         newString += String.fromCharCode(i+1);
         //console.log(String.fromCharCode(i+1));

    }
    else if(keyCode === 90)
    {
        //if it's a z being examined, add an a
         newString += "a";
    }
    else
        //it is a symbol, so just add it to the new string without change
        newString += str[i];
    }
  return newString.toUpperCase();

}

console.log(LetterChanges("Charlie"));

Upvotes: 0

Views: 592

Answers (2)

Muhammad Umer
Muhammad Umer

Reputation: 18097

Jsfiddle: http://jsfiddle.net/techsin/pnbuae83/1/

function codeIncreaser(input) {
    var str='', code=null;
    Array.prototype.forEach.call(input, function (e) {
        code = e.charCodeAt();
        if ((code>64 && code<90) || (code>96 && code<122)) {
            code++;
        } else if (code == 90) {
            code = 65;
        } else if (code == 122) {
            code = 97;
        }
        str += String.fromCharCode(code);
    });
    return str;
}

var text =  codeIncreaser('abczABC');
console.log(text);

This accommodates lowercase letters as well.

and if you wanna make code somewhat compact you could do something like this...

function $(i) {
    var s='', c;
    Array.prototype.forEach.call(i, function (e) {
        c = e.charCodeAt();
        ((c>64&&c<90)||(c>96&&c<122))?c++:((c == 90)?c=65:(c==122&&(c=97)));
        s += String.fromCharCode(c);
    });
    return s;
}

console.log($('abczABC @-@'));

Upvotes: 1

kindasimple
kindasimple

Reputation: 2427

change

newString += String.fromCharCode(i+1);

to

newString += String.fromCharCode(keyCode+1);

Upvotes: 2

Related Questions