Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char to Hex in javascript

Could anyone guide me on how to convert char to hex in javascript?

For example:

"入力されたデータは範囲外です。"
to
"\u5165\u529B\u3055\u308C\u305F\u30C7\u30FC\u30BF\u306F\u7BC4\u56F2\u5916\u3067\u3059\u3002"

This site does it

However I can not figure it out.

Any suggestion.

Thanks, Sarbbottam

like image 953
user626818 Avatar asked Apr 26 '11 05:04

user626818


People also ask

How do you write hex in JavaScript?

To convert a number to hexadecimal, call the toString() method on the number, passing it 16 as the base, e.g. num. toString(16) . The toString method takes the base as a parameter and returns the string representation of the number.

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 can loop through the characters and use the charCodeAt function to get their UTF-16 values, then constructing a string with them.

Here's some code I constructed that is much better than the code on the site you've linked, and should be easier to understand:

function string_as_unicode_escape(input) {
    function pad_four(input) {
        var l = input.length;
        if (l == 0) return '0000';
        if (l == 1) return '000' + input;
        if (l == 2) return '00' + input;
        if (l == 3) return '0' + input;
        return input;
    }
    var output = '';
    for (var i = 0, l = input.length; i < l; i++)
        output += '\\u' + pad_four(input.charCodeAt(i).toString(16));
    return output;
}

Let's break it down.

  1. string_as_unicode_escape takes one argument, input, which is a string.
  2. pad_four is an internal function that does one thing; it pads strings with leading '0' characters until the length is at least four characters long.
  3. Start off by defining output as an empty string.
  4. For each character in the string, append \u to the output string. Take the UTF-16 value of the character with input.charCodeAt(i), then convert it to a hexadecimal string with .toString(16), then pad it with leading zeros, then append the result to the output string.
  5. Return the output string.

As Tim Down commented, we can also add 0x10000 to the charCodeAt value and then .slice(1) the string resulting from calling .toString(16), to achieve the padding effect.

like image 199
Delan Azabani Avatar answered Oct 30 '22 19:10

Delan Azabani