Christian
Christian

Reputation: 3393

Display unicode characters (emojies) in Javascript

I have a database with tweets such as "\U0001f374 Lunch. Had loads of meat..." -- that is, with emojies represented as unicode (\U0001f374 is the knife&fork emoji). In my Web app I fetch tweets using Ajax requests and want to display them.

No big deal, and I have it so far up and running that I can display the "raw" tweet strings with the unicode. However, I like to render the emojies. How can I do this in Javascript?

Upvotes: 2

Views: 2459

Answers (1)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201518

Since a notation like \U0001f374 is undefined in JavaScript, you need to construct the character from it with your own code (or suitable library code). You could parse the Unicode number from the string and convert it to a pair of surrogate code points.

But if you are using JavaScript in the HTML (or XML) context, you could let the HTML (or XML) parser do the job. Just change the string (assumed to have 8 hex digits) to an HTML or XML character reference and make sure the result is parsed as markup:

var sample = document.getElementById('in').value;
sample = sample.replace(/\\U([0-9a-f]{8})/gi, "&#x$1;");
document.getElementById('demo').innerHTML = sample;
<input id=in size=40
       value="\U0001f374 Lunch. Had loads of meat...">
<div id=demo>To be replaced</div>

Upvotes: 3

Related Questions