javascripthtmlemojitwemoji

How to replace emojis in html with twemoji?


In user-generated posts, I have many raw emojis like

   <p>I ❤ your post!</p> 

I'm wondering what is the best way to replace these emojis with colorful emojis like:

 <p>I <i class="twa twa-heart">❤️</i> your post!</p>

I'd like to style the emojies with twemoji library.

You might ask why not let users insert the styled emojis at the first place while picking the emojis? The answer is that the interface's text editor is not WYSIWYG and the user posts are heavily stripped. So such option is ruled out and I'm looking for a solution that does this conversion at render time.


Solution

  • Check out the docs for twemoji.... https://github.com/twitter/twemoji#api

    API

    Following are all the methods exposed in the twemoji namespace.

    twemoji.parse( ... ) V1

    This is the main parsing utility and has 3 overloads per parsing type.

    There are mainly two kinds of parsing: string parsing and DOM parsing.

    You can parse strings (parse their input).

    I believe you're looking for smoething like this:

    However, for already sanitized strings, this method can be considered safe enough. Please see DOM parsing if security is one of your major concerns.

    twemoji.parse('I \u2764\uFE0F emoji!');
    
    // will produce
    /*
    I <img
      class="emoji"
      draggable="false"
      alt="❤️"
      src="https://twemoji.maxcdn.com/36x36/2764.png"/> emoji!
    */