DEV Community

Cover image for How to check if a string contains emojis in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to check if a string contains emojis in JavaScript?

Originally posted here!

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

TL;DR

// Match almost all emoji
const str = "Hello 😃 😄";
/(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/gi.test(
  str
);
Enter fullscreen mode Exit fullscreen mode

For detailed explanation. Read on 📖.

This is the regex expression for matching almost all the emojis in a string. This range of Unicode will match almost all the emoji's in a string.

// Regular expression to match emoji
const regexExp = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/gi;
Enter fullscreen mode Exit fullscreen mode

Now let's write a string with some emojis.

// Regular expression to match emoji
const regexExp = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/gi;

// String with 3 emoji and some letters
const str = "Hello 😃 😄";
Enter fullscreen mode Exit fullscreen mode

Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,

// Regular expression to match emoji
const regexExp = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/gi;

// String with 3 emoji and some letters
const str = "Hello 😃 😄";

regexExp.test(str); // true
Enter fullscreen mode Exit fullscreen mode
  • The test() method will accept a string type as an argument to test for a match.
  • The method will return boolean true if there is a match using the regular expression and false if not.

See the above example live in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)