Replacing Emojis with HTML Entities

Thursday, 20 June 2019

This week I came across a case where using an emoji in my code broke a page I was working on (I suspected the emoji was causing an error in the database which stopped the rest of the page from rendering). Therefore I wanted to share a way that you can replace any emoji in a string with the HTML entity equivalent which works flawlessly. This post is only going to be a short one since I don’t want to deep dive into Unicode and the pros and cons of such a format but make rather give you a solution can use in such a situation.

Lets jump in…

let emojiUnicode = (input) => {
  return emojiUnicode.raw(input).toString('16')

emojiUnicode.raw = function (input) {
  if (input.length === 1) {
    return input.charCodeAt(0)
  let comp =
    (input.charCodeAt(0) - 0xd800) * 0x400 +
    (input.charCodeAt(1) - 0xdc00) +
  if (comp < 0) {
    return input.charCodeAt(0)
  return comp

So above is a function to convert any emoji passed in as an argument to a Unicode string, taken from the emoji-unicode npm package (thanks to ionicabizau for creating the package)

But now we need to find a way to grab all of the emojis in a string, pass them into the function and replace each emoji with the HTML entity.

export const convertEmojis = (string) => {
  var regex =
  let emojis = string.match(regex)

  if (emojis) {
    let convertedEmojis = => {
      return emojiUnicode(e)

    let index = 0

    return string.replace(regex, function () {
      let unicodeEmoji = `&#x${convertedEmojis[index]};`
      return `${unicodeEmoji}`

  return string

First of all we create a regex to find all of the emojis in the string, taken from Kevin Scott’s great post emojis in javascript. If we then get a match in the string we map through the returned array converting and returning each value as a Unicode value. We then take our string and replace each emoji with the Unicode value prepended with &#x and appended with a ; which turns our Unicode string into a HTML entity. Note ; tells the browser that it is the end of the entity.

And that’s it! Super simple but super effective in converting your emojis in astring.

Hope you enjoyed and let me know your thoughts