How to reverse String.fromCharCode?

'H'.charCodeAt(0)

Use charCodeAt:

var str = 'H';
var charcode = str.charCodeAt(0);

@Silvio's answer is only true for code points up to 0xFFFF (which in the end is the maximum that String.fromCharCode can output). You can't always assume the length of a character is one:

'𐌰'.length
-> 2

Here's something that works:

var utf16ToDig = function(s) {
    var length = s.length;
    var index = -1;
    var result = "";
    var hex;
    while (++index < length) {
        hex = s.charCodeAt(index).toString(16).toUpperCase();
        result += ('0000' + hex).slice(-4);
    }
    return parseInt(result, 16);
}

Using it:

utf16ToDig('𐌰').toString(16)
-> "d800df30"

(Inspiration from https://mothereff.in/utf-8)


You can define your own global functions like this:

function CHR(ord)
{
    return String.fromCharCode(ord);
}

function ORD(chr)
{
    return chr.charCodeAt(0);
}

Then use them like this:

var mySTR = CHR(72);

or

var myNUM = ORD('H');

(If you want to use them more than once, and/or a lot in your code.)