Forked from thekevinscott/gist:54dec813e12e7984d17e1badc30b930c
Created
May 27, 2019 03:14
-
-
Save bds/19f165665e31467595e2e86635f90a65 to your computer and use it in GitHub Desktop.
Unicoding emoji
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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