Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bds/19f165665e31467595e2e86635f90a65 to your computer and use it in GitHub Desktop.
Save bds/19f165665e31467595e2e86635f90a65 to your computer and use it in GitHub Desktop.
Unicoding emoji
// http://www.2ality.com/2013/09/javascript-unicode.html
function toUTF16(codePoint) {
var TEN_BITS = parseInt('1111111111', 2);
function u(codeUnit) {
return '\\u'+codeUnit.toString(16).toUpperCase();
}
if (codePoint <= 0xFFFF) {
return u(codePoint);
}
codePoint -= 0x10000;
// Shift right to get to most significant 10 bits
var leadSurrogate = 0xD800 + (codePoint >> 10);
// Mask to get least significant 10 bits
var tailSurrogate = 0xDC00 + (codePoint & TEN_BITS);
return u(leadSurrogate) + u(tailSurrogate);
}
// using codePointAt, it's easy to go from emoji
// to decimal and back.
// Emoji to decimal representation
"😀".codePointAt(0)
>128512
// Decimal to emoji
String.fromCodePoint(128512)
>"😀"
// going from emoji to hexadecimal is a little
// bit trickier. To convert from decimal to hexadecimal,
// we can use toUTF16.
// Decimal to hexadecimal
toUTF16(128512)
> "\uD83D\uDE00"
// Hexadecimal to emoji
"\uD83D\uDE00"
> "😀"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment