How to Search for Emojis with Regular Expressions
ยทโ๏ธ๏ธ 3 mins read
Indieweb! This article has been mentioned: 9 times!
Turns out the documentation on MDN wasn't complete for this piece. But there is such a thing as Unicode property escapes. And I was astonished when I found out there is a shorthand for Emojis in there!
I said it wasn't really complete because you need to pass the Unicode flag (u
) in your RegExp
for this to work.
Here's the code snippet.
'Hey, there! ๐ธ'.match(/\\p{Emoji}/u)
(Notice the u
at the end.)
And this will be the output:
["๐ธ", index: 12, input: "Hey, there! ๐ธ", groups: undefined]
The first element in the Array is the actual "match".
There are special cases, tho. Skin tones for example, as you may know, are a sum (or "ligature") of two characters according to the unicode spec: the original emoji plus a modifier:
> '๐๐พ'.match(/\\p{Emoji}/ug)
< (2) ["๐", "๐พ"]
This case is a little bit trickier, because, you'll need to take into consideration also the modifiers:
- ๐ป U+1F3FB (
'\uD83C\uDFFB'
in JS): "Light" (types 1 or 2 in the Fitzpatrick Scale) - ๐ผ U+1F3FC (
'\uD83C\uDFFC'
in JS): "Medium-Light" (type 3) - ๐ฝ U+1F3FD (
'\uD83C\uDFFD'
in JS): "Medium" (type 4) - ๐พ U+1F3FE (
'\uD83C\uDFFE'
in JS): "Medium-Dark" (type 5) - ๐ฟ U+1F3FF (
'\uD83C\uDFFF'
in JS): "Dark" (type 6)
To catch the modifiers, notice how I had to pass also the g
flag to get "all" the emojis from the string (because Regexp in JS works that way, if the "global" flag is not passed it stops when the first match is reached).
This is way, way, handier than passing the Unicode characters range that Emoji covers as many libraries do, IMO, so it was worth sharing with you!
Happy emoji searching!