Char to Hex in javascript
function string_as_unicode_escape(str){
return str.split("").map(function(s){
return "\\u"+("0000" + s.charCodeAt(0).toString(16)).slice(-4);
}).join("");
}
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.- Start off by defining
output
as an empty string. - For each character in the string, append
\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. - 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.