2

When I try to use a string template to generate an emoji I get an error.

How to achieve this purpose?

Javascript code:

const unifiedValue = '1F60E';
const emoji = `\u{${ unifiedValue }}`;

Javascript error:

SyntaxError: Invalid escape sequence in template

Of course if I use the value directly it works, but that would be error-prone + thousands lines of code with hundreds of if conditions.

Developer console:

'\u{1F60E}'

Console Output: "😎"

1

2 Answers 2

11

Use fromCodePoint function.

Here is a wroking solution

const unifiedValue = '1F60E';

var emoji = `0x${unifiedValue}`;
emoji = String.fromCodePoint(emoji);

console.log(emoji);

Also keep in mind that our "beloved" internet explorer does not support it :/

enter image description here

EDIT

const unifiedValue = '1F60E';

var emoji = parseInt(unifiedValue, 16);

emoji = String.fromCodePoint(emoji);

console.log(emoji);

3
  • much beloved internet explorer is not important for us :) this worked great! thank you
    – sertsedat
    May 16, 2018 at 11:44
  • 1
    Don't use `0x${unifiedValue}`. Just use parseInt(unifiedValue, 16).
    – Bergi
    May 16, 2018 at 12:09
  • @Bergi Good point, edited answer May 16, 2018 at 12:10
0

I think the problem here is you used template quote. You must use double backslash in template quote.

const emoji = `\u{${ unifiedValue }}`;

Instead of this

const emoji = `\\u{${ unifiedValue }}`;
2
  • 1
    But it returns string: \u{1F60E} instead of emoticon May 16, 2018 at 11:29
  • @KrzysztofJaniszewski is right, double quote would espace backlash and return string \u{1F60E} instead, not 😎
    – sertsedat
    May 16, 2018 at 11:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.