mathiasbynens / emoji-regex

A regular expression to match all Emoji-only symbols as per the Unicode Standard.
https://mths.be/emoji-regex
MIT License
1.72k stars 175 forks source link

How can I use this library to match all-emoji strings? i.e. strings consisting of emoji characters only #64

Closed debajit closed 3 years ago

debajit commented 4 years ago

I'm writing a chat-like application, and I need to check if a string consists only of Emoji characters, so that I could render the emoji in large text.

Currently I'm using a function like the following to do this:

function isEmojiOnly(text, emojiRegex) {
  const textOnly = text.replace(/\s/g, "")
  return textOnly.replace(emojiRegex, "") === ""
}

Does the emoji-regex library offer any provision to do this more optimally?

mxstbr commented 4 years ago

You have to mangle the regexp a bit, we did a similar thing for Spectrum. See the source here: https://github.com/withspectrum/spectrum/blob/alpha/shared/only-contains-emoji.js

Hope that helps!

OlivierFreyssinet-old commented 4 years ago

Did it like this:

// beginText ( (whitespace*)(emoji+)(whitespace*) )+ endText
emojiOnlyRegExp = new RegExp(`^(\\s*(${emojiRegex().source})+\\s*)+$`)

This solution matches strings that have only emojis and whitespaces, but doesn't match strings with only whitespace

EDIT: DON'T USE THIS!! The JS thread was getting completely blocked in my app and it took me a lot of time to find out that it was because of this RegExp 😬 You can check the "safety" of a regular expression with this tool https://github.com/substack/safe-regex, as I did here: https://runkit.com/embed/evlykbmh8n1m

chmiiller commented 3 years ago

This is very useful and yeah, would be nice to have it out of the box from the lib

mathiasbynens commented 3 years ago

You could matchAllIf you only want to render the emoji in large text when the input consists of a single emoji (or single emoji sequence, i.e. visually a single glyph), then you could simply apply the regex and see if the match === the original string.

If you want to cover the case where the input consists of multiple, separate emoji (like in your isEmojiOnly('👍👏') example), you can get the emojiRegex().source and wrap it in ^ and $ like @mxstbr showed.