This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
When dealing with user-generated content, there's a high chance that you have to deal with strings full of Emojis. Emoji rendering can come with challenges, so you may want to detect when strings include Emojis and replace them with images.
Let's find out how to spot all these cute symbols!
Luckily, JavaScript regular expressions come with a Unicode mode these days.
MDN describes that Unicode mode treats a regular expression pattern as a sequence of Unicode code points instead of code units.
There's more to it, though. When you enable Unicode mode in a regular expression, you can also use Unicode property escapes. Unicode property escapes (\p{}
or \P{}
) allow you to match Unicode characters based on their properties and characteristics.
That's right; you can match currency symbols, non-Latin characters, and, you guessed it, Emojis!
Here's an example snippet:
const emojiRegex = /\p{Emoji}/u;
emojiRegex.test('⭐'); // true
// The capital 'p' negates the match
const noEmojiRegex = /\P{Emoji}/u;
noEmojiRegex.test('⭐'); // false
If you want to replace and alter Emojis in JavaScript strings, you can do that with String.replaceAll
, too.
// Note the 'g' flag to replace allEmojis
'🙈–👍–⭐'.replaceAll(/\p{Emoji}/ug, '_'); // '_–_–_'
The browser support looks pretty good for Unicode property escapes, too!
If you have comments on this topic, please give me a shoutout on Twitter or write me a good old email. I'm keen on learning more about it!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2021-11-17T23:00:00+00:00) How to detect Emojis in JavaScript strings (#snippet). Retrieved from https://www.scien.cx/2021/11/17/how-to-detect-emojis-in-javascript-strings-snippet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.