Urgent.News

What's breaking now, across thousands of outlets.

Tech

Why "๐Ÿ‘จ๐Ÿ‘ฉ๐Ÿ‘ง๐Ÿ‘ฆ".length Is 11: Counting Characters the Way Users See Them

Our word counter had a bug that no unit test caught: it said the family emoji ๐Ÿ‘จ๐Ÿ‘ฉ๐Ÿ‘ง๐Ÿ‘ฆ is 11 characters . Users see one. If you build anything with a character limit (captions, bios, SMS, form fields), you probably have the same bug, because the default way to count a string in JavaScript counts something users never see. The test We ran seven strings through four ways of counting: Text .lengthโ€ฆ

JavaScript's default `string.length` method counts UTF-16 code units, not what users actually see. This led to an error when counting the emoji family ๐Ÿ‘จ๐Ÿ‘ฉ๐Ÿ‘ง๐Ÿ‘ฆ, which JavaScript reported as 11 characters. Users only see one character in this emoji. To fix this bug, we need to count graphemes, which represent what a user perceives as a single character.

Unicode defines graphemes, or extended grapheme clusters, as the building blocks of text that users recognize as individual characters. There are multiple ways to count graphemes in JavaScript. The most straightforward method is using the built-in `Intl.Segmenter` in modern browsers and Node.js. We first create a grapheme segmenter object, then use the `segment()` method to split the string into individual graphemes.

Finally, we count the number of resulting segments. For compatibility with older browsers, we can fall back to counting code points, which is still more accurate than using `string.length`. When counting characters for user input, such as captions, bios, SMS, or form fields, it's essential to use graphemes instead of raw code points to ensure users can see and edit what they're typing.

For third-party limits or database columns, use UTF-8 byte count or the platform's specific counting method. The provided code snippets demonstrate how to implement a grapheme counter in JavaScript, ensuring accurate character counts across various platforms and use cases.

Written by urgent.news from Dev.to's reporting โ€” not their text. Machine-written โ€” may contain errors; check the original before relying on it.

Read the original at dev.to โ†’

More in Tech

How to read PostgreSQL EXPLAIN output

TL;DR Read the plan tree from leaves to root; cost, rows, and width are estimates, not measurements. Start with plain EXPLAIN when execution consequences are unknown.

More from Wednesday 4 November โ†’