Reputation: 340
I'm trying to setup an emoji picker control for a form that will post to various social media networks. I am trying to implement emojione-picker
(https://github.com/tommoor/emojione-picker) which provides a data
object that looks like this when you click on an emoji icon:
{
"unicode":"1f600",
"unicode_alternates":"",
"name":"grinning face",
"shortname":":grinning:",
...
}
I don't want to use the shortname
property, but rather the unicode
value for the actual emoji. I want to insert the unicode value at the current cursor position of a <textarea>
on the page. I'm using the form value to post to Twitter which expect the actual emoji character (not :smile: or \u1f600 )
After reading this article (http://crocodillon.com/blog/parsing-emoji-unicode-in-javascript), I found that I can use a findSerrogatePair method to convert the unicode value into the escape sequence (?) Like this:
function findSurrogatePair(point) {
// assumes point > 0xffff
var offset = point - 0x10000,
lead = 0xd800 + (offset >> 10),
trail = 0xdc00 + (offset & 0x3ff);
return [lead.toString(16), trail.toString(16)];
}
Then I tried this:
foo = findSurrogatePair('0x1f600') => ["d83d", "de00"]
Using these values, I can see the actual smiley face character log to the console:
console.log("\ud83d\ude00")
=> (actual smily emoji)
But if I try to read the values from foo
and add the \u, I see the character code:
console.log("\\u" + foo[0] + "\\u" + foo[1])
=> "\ud83d\ude00"
If I just use a single backslash:
console.log("\u" + foo[0] + "\u" + foo[1])
I get this error:
Uncaught SyntaxError: Unexpected token ILLEGAL(…)
Upvotes: 1
Views: 3148
Reputation: 4380
More concise way:
function findSurrogatePair(point) {
var offset = point - 0x10000,
lead = 0xd800 + (offset >> 10),
trail = 0xdc00 + (offset & 0x3ff);
return String.fromCharCode(lead) + String.fromCharCode(trail);
}
credit to: jnes
Upvotes: 0
Reputation: 1083
Use String.fromCharCode:
findSurrogatePair(0x1f600)
.map((el) => parseInt(el, 16))
.map((el) => String.fromCharCode(el))
.join('')
But then you're converting number to string in findSurrogatePair
and the n back to number here with parseInt
..
Upvotes: 2