JavaScript

How to check if a string contains emojis in JavaScript?

Advertisements

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:

'\u{1F60A}' // "😊"
'\u{1F42A}' // "πŸͺ"
JavaScript

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
JavaScript

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'
JavaScript

The β€œg” flag was used to replace all emojis.

It is worth noting that some emojis are a combination of multiple emojis (or code points). So, this is not a fail-safe approach and there can be some more nuances:

"πŸ‡―πŸ‡΅".replaceAll(/\p{Emoji}/gu, '-'); // '--'
"πŸ™‹πŸΏ".replaceAll(/\p{Emoji}/gu, '-'); // '--'
"πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦".replaceAll(/\p{Emoji}/gu, '-'); // '----'
JavaScript

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.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCRΒ which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria
Tags: javascript

Recent Posts

Remapping keyboard keys to avoid Carpal Tunnel

I am terrible at optimizing my keyboard layout for anything. But off lately, my little…

3 days ago

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

4 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

5 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

5 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

6 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

7 months ago
Advertisements