brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Intl.Segmenter counts characters the way people see them, emoji included

Javascript
~/tips/tip-js-intl-segmenter-count-characters

const text = "👍🏽 ok 🇳🇱";

Get a real character count for limits and truncation, where string length is wrong.

A thumbs up emoji with a skin tone has a length of 4 in JavaScript. For a character counter under a text field that is plainly wrong. Intl.Segmenter splits text into what a reader sees as single characters.

const text = "👍🏽 ok 🇳🇱";
text.length; // 12

const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });
[...graphemes.segment(text)].length; // 6

const words = new Intl.Segmenter("nl", { granularity: "word" });
[...words.segment("Dit is een zin, met woorden.")]
  .filter((s) => s.isWordLike).length; // 6

length counts UTF-16 code units. Emoji with modifiers, flags and letters with combining accents use several of them. With granularity: "grapheme" the segmenter groups them into user-perceived characters, so the flag counts as one. Spreading [...str] is better than length but still counts the flag as two.

I also like the word granularity for word counts. It handles languages without spaces between words, like Japanese, where splitting on spaces does nothing. isWordLike filters out spaces and punctuation.

Support: Chrome 87, Safari 14.1, and Firefox only since version 125. A caveat for limits: your database may count differently. If a column allows 280 characters in bytes or code units, a grapheme counter in the browser will let through text that the server rejects, so check what the backend actually counts.

Further reading: MDN: Intl.Segmenter

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link