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"
However I can not figure it out.
Any suggestion.
Thanks, Sarbbottam
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:
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 theoutput
string. Take the UTF-16 value of the character withinput.charCodeAt(i)
, then convert it to a hexadecimal string with.toString(16)
, then pad it with leading zeros, then append the result to theoutput
string.output
string.As Tim Down commented, we can also add
0x10000
to thecharCodeAt
value and then.slice(1)
the string resulting from calling.toString(16)
, to achieve the padding effect.var hex=new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
//------------------------ lo llamarias con