Image by Mega Pixel via Shutterstock

How Long Is a Pirate Flag?

Calculating Emoji Length in JavaScript

Faraz Kelhini
3 min readJun 9, 2023

--

https://pragprog.com/newsletter/
https://pragprog.com/newsletter/

Take a look at the following code example. Can you guess what the output might be? Take a shot before reading further!

console.log("🏴‍☠️".length);

The output of this code is actually 5, which might not be what you were expecting.

In JavaScript, some characters and emojis are formed by multiple code units, which can lead to unexpected results when using the length property.

The emoji 🏴‍☠️ is called an Emoji ZWJ Sequence, and it’s made up of two separate emojis: 🏴 and ☠. When a zero-width joiner (ZWJ) is placed between these emojis, they are displayed as a connected sequence on platforms that support it. The ZWJ itself is a non-printing character that enables this connected display.

Isn’t it fascinating how different emojis can come together to form a unique emoji?

The length of the string “🏴‍☠️” is 5 because the length property counts the code unit of each independent emoji as well as the zero-width joiner (ZWJ) required to connect them.

To learn more about code units, see mdn web docs.

But, here’s some good news! To tackle this issue, we have the Internationalization API that comes to the rescue. It provides a handy method called Segmenter(). This method helps you segment strings properly, taking into account the intended segmentation rules of various languages and scripts.

With the Segmenter() method, you can properly calculate the length of a string containing emojis:

function getLength(str) {
return [...new Intl.Segmenter().segment(str)].length;
}
getLength("🏴‍☠️"); // => 1

The Internationalization API is really clever when it comes to counting ZWJ emojis. It treats them as a single character, which makes things much easier for us!

In my book, I’ve delved into the Segmenter() method and other fascinating Internationalization APIs in great detail. If you want to learn more and explore other cool features, you’ll find a wealth of information in Text Processing with JavaScript: Regular Expressions, Tools, and Techniques for Optimal Performance! 😊

Now in beta from The Pragmatic Bookshelf:

During the beta period, we invite you to make comments and suggestions on the book’s page on DevTalk, where you will also find a promo code that saves you 35 percent on the ebook.

Dark book cover with a butterfly made of blue, green, yellow, and pink words that are related to text processing in JavaScript.

--

--

Faraz Kelhini
The Pragmatic Programmers

Faraz is a professional JavaScript developer who is passionate about promoting patterns and ideas that make web development more productive. Website: eloux.com