Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Find Emoji in String and Parse

After TONS of research, I have found how to parse emoji in realtime using the Twemoji library.

Now, I need to figure out how to identify if there's emoji within some text, grab the position of that emoji and execute the parsing function.

Some example text can be

It is a great day ๐Ÿ˜€.

Need to find the ๐Ÿ˜€ within the whole string and use the following function to get its hex code, return the surrogate pairs and parse with the Twemoji library.

function entityForSymbolInContainer(selector) {
    var code = data.message.body.codePointAt(0);
    var codeHex = code.toString(16);
    while (codeHex.length < 4) {
        codeHex = "0" + codeHex;
    }

    return codeHex;
}

// Get emoji hex code
    var emoji = entityForSymbolInContainer(data.message.body);
// For given an HEX codepoint, returns UTF16 surrogate pairs
    var emoji = twemoji.convert.fromCodePoint(emoji);
// Given a generic string, it will replace all emoji with an <img> tag
    var emoji = twemoji.parse(emoji);

I am using the following check to see if there's emoji within the text. Problem is that for a simple grinning face (๐Ÿ˜€) it doesn't alert me. However, if I type in the "shirt and tie" (๐Ÿ‘”) it will alert me to that.

var string = "It is a great day ๐Ÿ˜€.";
var emojiRegex = /([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g;

if (string.match(emojiRegex)) {
    alert("emoji found");
}

Please help on the issue of the regex not picking up the emoji. After that, I should be able to just find that within the string.

Thank you!

like image 912
Matt Pierce Avatar asked May 07 '16 13:05

Matt Pierce


People also ask

How do you check emojis with strings?

Swift 5 Scalars have isEmoji and isEmojiPresentation properties that will help to find emoji in particular String. isEmoji - Boolean value indicating whether the scalar has an emoji presentation, whether or not it is the default.

How do you check if a string is an emoji in JS?

To check if a string contains emojis in JavaScript, we can use a regex expression to match a range of Unicode specific to emojis.

Does regex work with emojis?

Does regex work with Emojis? emoji-regex offers a regular expression to match all emoji symbols and sequences (including textual representations of emoji) as per the Unicode Standard. It's based on emoji-test-regex-pattern, which generates (at build time) the regular expression pattern based on the Unicode Standard.


1 Answers

Nowadays with ES2018 we can use Unicode Property Escapes in a regex match:

\p{โ€ฆ}

For simple emojis it would be:

"Be kind ๐Ÿ˜Š, smile".match(/\p{Emoji}+/gu)

For emojis including glyphs glued with ZERO WIDTH JOINER like ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ it can be:

"My Family ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ".match(/[\p{Emoji}\u200d]+/gu)
like image 126
Litzer Avatar answered Sep 17 '22 15:09

Litzer