David Spector
David Spector

Reputation: 1671

Why does this code display incorrect Unicode?

The following minimal code creates a string containing a dog emoji and red heart emoji. It then paws through the string, showing the second emoji, the red heart. Why is a black heart shown (on Firefox) instead?

var u='\ud83d\udc0e\u2764';
var count=0;
for (let point of u)
    if (count++)
        alert(u+": "+point);

Upvotes: 2

Views: 804

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595402

U+2764 HEAVY BLACK HEART predates color emojis, and so it is a black heart when treated by itself. To make it red, join it with U+FE0F VARIATION SELECTOR-16, eg:

var u='\ud83d\udc0e\u2764\ufe0f';

However, your for loop would ignore the \ufe0f and still just display \u2764 by itself, since they are separate codepoints.

Tweak your loop to peek the next codepoint after u and include it if it is a variable selector:

alert("\u2764"); // black heart
alert("\u2764\ufe0f"); // red heart

Upvotes: 4

Related Questions