How to check if a string contains emojis in JavaScript?

If you have user-generated content in your web application, chances are you have to deal with strings containing emojis. Since emojis are stored as Unicode, chances are that we want to detect these in our code and then render them accordingly. This article discusses how we can check if a string contains emojis in JavaScript.

A Unicode representation of emojis looks something like this:

- Advertisement -
'\u{1F60A}' // "๐Ÿ˜Š"
'\u{1F42A}' // "๐Ÿช"

And JavaScript regular expressions have a Unicode mode now, so we can use Unicode property escapes to check for various things like emojis and currency symbols.

const emojiRegex = /\p{Emoji}/u;
emojiRegex.test('๐Ÿ˜Š'); // true

And it has good browser support as well:

And if we wanted to do a replace, we can do:

'replacing emojis ๐Ÿ˜Š๐Ÿช'.replaceAll(/\p{Emoji}/ug, ''); // 'replacing emojis'

The “g” flag was used to replace all emojis.

It is worth noticing though that some emojis are a combination of multiple emojis (or code points). So this is not a fail-safe approach and needs some more nuances:

"๐Ÿ‡ฏ๐Ÿ‡ต".replaceAll(/\p{Emoji}/gu, '-'); // '--'
"๐Ÿ™‹๐Ÿฟ".replaceAll(/\p{Emoji}/gu, '-'); // '--'
"๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ".replaceAll(/\p{Emoji}/gu, '-'); // '----'

The country flags are a combination of regional symbol indicator letters” (๐Ÿ‡ฏ + ๐Ÿ‡ต), the emoji followed by a skin tone modifier is again a combination and the family one is a combination of 4 different emojis.

Recent Articles

Overriding nested dependencies in NPM

Whenever we install a particular package, it is common to come across a problem with a dependency's dependency. With the release of...

Automatic batching in React 18 helps avoid re-rendering

Remember the earlier versions of React that used to batch multiple state updates inside event handlers such as click or change to...

Flatten Arrays in Vanilla JavaScript with flat() and flatMap()

ES2019 introduced two methods on the array prototype that would make life so much simpler for developers. These are flat() and flatmap()...

Using GroupBy on an array of objects in JavaScript

Array grouping is a fairly common operation in any project. Until recently, we had to resort to either writing our own implementation...

Node.js introduces node: protocol imports

Node.js recently introduced a node: protocol for built-in modules. Built-in node modules can now be imported by prefixing the node: protocol prefix.

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.