Yet Another JavaScript Unicode Encode/Decode

Posted at



/* convert 🙌 to \\uD83D\\uDE4C */
function text_to_unicode(string) {
'use strict';

function is_whitespace(c) { return 9 === c || 10 === c || 13 === c || 32 === c; }
function left_pad(string) { return Array(4).concat(string).join('0').slice(-1 * Math.max(4, string.length)); }

string = string.split('').map(function(c){ return "\\\\u" + left_pad(c.charCodeAt(0).toString(16).toUpperCase()); }).join('');

return string;
}

/* convert \\uD83D\\uDE4C to 🙌 */
function unicode_to_text(string) {
var prefix = "\\\\\\\\u"
, regex = new RegExp(prefix + "([\\da-f]{4})","ig")
;

string = string.replace(regex, function(match, backtrace1){
return String.fromCharCode( parseInt(backtrace1, 16) )
});

return string;
}