Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kosso/9dc9df367f68f1d7ebbca07ee6e20683 to your computer and use it in GitHub Desktop.
Save kosso/9dc9df367f68f1d7ebbca07ee6e20683 to your computer and use it in GitHub Desktop.
Unicoding emoji
// see: https://medium.com/reactnative/emojis-in-javascript-f693d0eb79fb
// 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