JavaScript Snippet - Format As Unicode String ("\\u..")

Posted at

function to_unicode_format(str){
str = "\\\\u" + str.split("").map(function(c){
c = c.charCodeAt(0);
c = c.toString(16);
c = ("0000" + c).substr(-4)
return c;
}).join("\\\\u");
return str;
}


In this case using the unescape(encodeURIComponent("א")); to pre-format the character into a valid byte string (and later using decodeURIComponent(escape(.......)); to convert it back from byte-string) is not required at all,
The method above supports input in all of the Unicode-encoded character-sets ("א",...),
and will output a valid (ASCII compatible) Unicode-formatted characters that looks like \\u.....


bookmarklet version (yet so much minified):
javascript:(function(s){
s = prompt("∞ to Unicode-Format:","❝Likė A Ƀoŝš❞");
if(null === s || "" === s) return;
s = "\\\\u"
+ Array.prototype.map.call(s, function(c){
return ("0000" + c.charCodeAt(0).toString(16)).substr(-4);
}).join("\\\\u");
prompt("output:",s);
}());


bookmarklet minified:

javascript:(function(s){if(null===s||""===s)return;s="\\\\u"+s.split("").map(function(c){return ("0000" + c.charCodeAt(0).toString(16)).substr(-4);}).join("\\\\u");prompt("output:",s);}(prompt("∞ to Unicode-Format:","❝Likė A Ƀoŝš❞")));