How to check if a string contains emojis in JavaScript?
MELVIN GEORGE
Posted on February 15, 2021
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
);
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;
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 π π";
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
- The
test()
method will accept astring
type as an argument to test for a match. - The method will return boolean
true
if there is a match using the regular expression andfalse
if not.
See the above example live in JSBin.
Feel free to share if you found this useful π.
π πͺ π
π©
MELVIN GEORGE
Posted on February 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.