Search code examples
javascriptutf-8character-encodingutfchars

Converting unicode to hex


I have cyrillic word in my js file which charset is UTF-8 without BOM. How can I get hex index of unicode table of my first character? The word "Абв" and result must return hex code "0x0410".

I tried this code, but it returns wrong result:

var code = "А".charCodeAt(0);
var codeHex = code.toString(16).toUpperCase();
console.log(code, codeHex);

Solution

  • Note that in your console.log(code, codeHex); you have no space between the two values code and codeHex, so you'll get to see a seemingly big value (1040410).

    So separate like this:

    console.log(code, ' ', codeHex);
    

    and if you want a nice hex formatting, do this:

    console.log(code, ' ', '0x' + ('0000' + codeHex).substr(-4));
    

    Snippet:

    var code = "А".charCodeAt(0);
    var codeHex = code.toString(16).toUpperCase();
    document.write(code, ' ', '0x' + ('0000' + codeHex).substr(-4));