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
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.
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.
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.
string_as_unicode_escape
takes one argument, input
, which is a string.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.output
as an empty string.\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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With