简体   繁体   中英

Convert escaped unicode sequence to Emoji in JS

I have a string in JS as follows. I am having a hard time converting these surrogate pairs to emoji's. Can someone help?

I have tried to get a solution online by searching almost everything that I could, but in vain.

var text = 'CONGRATS! Your task has been completed! Tell us how we did \\uD83D\\uDE4C \\uD83D\\uDC4D \\uD83D\\uDC4E'

This is a node.js code. Is there any easy way to convert these codes to emojis without using an external helper utility?

EDIT:

I updated my code and the regex as follows:

var text = 'CONGRATS! Your task has been completed! Tell us how we did {2722} {1F44D} {1F44E}';

text.replace(/\{[^}]*\}/ig, (_, g) => String.fromCodePoint(`0x${g}`))

What am I doing wrong?

One option could be to replace all Unicode escape sequences with their HEX representations and use String.fromCharCode() to replace it with its associated character:

 const text = 'CONGRATS! Your task has been completed! Tell us how we did \\\?\\\? \\\?\\\? \\\?\\\?'; const res = text.replace(/\\\\u([0-9A-F]{4})/ig, (_, g) => String.fromCharCode(`0x${g}`)); console.log(res);

As for your edit, your issue is with your regular expression. You can change it to be /\\{([^}]*)\\}/g , which means:

  1. \\{ - match an open curly brace.
  2. ([^}]*) - match and group the contents after the open curly brace which is not a closed curly brace } .
  3. } - match a closed curly brace.
  4. g - match the expression globally (so all occurrences of the expression, not just the first)

The entire regular expression will match {CONTENTS} , whereas the group will contain only the contents between the two curly braces, so CONTENTS . The match is the first argument provided to the .replace() callback function whereas the group ( g ) is provided as the second argument and is what we use:

 const text = 'CONGRATS! Your task has been completed! Tell us how we did {2722} {1F44D} {1F44E}'; const res = text.replace(/\\{([^}]*)\\}/g, (_, g) => String.fromCodePoint(`0x${g}`)); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM