😱 Emoji OMG

Pulling an emoji from text isn't super straightforward. There's no special character for emoji in regex.

I'd like to start replacing the favicon for the page with a favicon found in the <h1> of the current section. So the first step is determining if there's an emoji in the <h1> at all. However, this task is tricker than it seems. EVERYTHING online indicates the best solution is a LONG LONG string of regex which tests the unicode data.

I'll do some research and see if I can find a better way to do determine if a character is regex.


My Findings!

The typical advice you'll find online when searching for how to determine if a character is an emoji is to use RegEx, but I've found a MUCH easier way!

Strings in js can be split into characters, and with the spread operator, it's easy!

Splitting a String into Chars

    const string = "🤖: Hello World! 👋";
const charList = [...string]; // [ "🤖", ":", " ", "H" [[...]] , "d", "!", " ", "👋" ]

Which doesn't mean much on it's own. Frankly, it's more cumbersome to deal with. BUT! Javascript did something interesting! It didn't split up ALL the characters! As you can see from the any emoji regex example, Emojis are comprised of MANY characters! Those characters will render as a single, emoji.

So JS is put in a weird position. The EXPECTED behavior of splitting a string, is accomplished. Yet, the LENGTH of each character, is technically different! Since Emojis are just unicode data rendered in a particular way, splitting a string does something fascinating in JS.

    "🤖".length; // outputs: 2
"👋".length; // outputs: 2
"📌".length; // outputs: 2

What it means!

Because JS splits a string by what is rendered, not by how it's represented in data, String.length does something super fascinating! It will give back a value greater than 1 for emojis!

With this interesting tidbit, you can determine if a character in a string is an emoji! Furthermore, you are able to use the many Array Methods to deal with the characters!

    const string = "🤖: Hello World! 👋";
const charList = [...string];
charList.some(char => char.length > 1) // charList contains an emoji
charList.filter(char => char.length > 1) // return an array of all of the emojis in charList
charList.find(char => char.length > 1) // return the first emoji in charList

I hope you found this helpful! I know it's much easier for me to deal with Emojis now.