Skip to content
Adrien Hubert

How long is a string?

Depends who is counting. A reader counts what they see. JavaScript counts UTF-16 code units. A database column usually counts bytes, while Unicode itself counts code points. Type or paste below. Each box is one grapheme, the thing a cursor steps over. Inside it are the code points that build it. Click one to see its bytes.

Try
Transform
0graphemes
0code points
0UTF-16 units, JS .length
0UTF-8 bytes

Note

The first preset is the word café written twice. The first copy uses U+00E9, a single code point for e with an acute accent. The second uses a plain e followed by U+0301, a combining accent that attaches to whatever came before it. They render the same, compare as different, and only the second one has a length of 5 in JavaScript. NFC folds the pair into the single code point, NFD splits it apart, and after either one the two words are equal.

The K forms go further and also fold compatibility characters. The ligature fi turns into two separate letters. The fraction one half turns into a 1, a fraction slash and a 2, and the circled 1 loses its circle. That is useful for search and destructive for storage, which is why the K forms are a choice and not a default.

Case mapping can change length too. Uppercase ß is SS, so one grapheme becomes two. Lowercase İ, the Turkish dotted capital, becomes an i followed by a combining dot above, because the default mapping does not know the text is Turkish. The lookalike preset swaps one Latin o for a Cyrillic one. Nothing on screen changes except the script line, which is the kind of check that browsers run on domain names before showing them.

Grapheme boundaries come from Intl.Segmenter, which follows UAX #29 as shipped with your browser. Recent versions keep a whole Devanagari conjunct together, so the last box of नमस्ते holds four code points. Older engines split it in two. Categories and scripts come from regular expression property escapes such as \p{gc=Mn}, tested one by one, since the browser exposes no character database directly. Character names are not available that way, so the inspector shows the category instead.

I do not see any of these units. My input arrives as tokens built from UTF-8 bytes, which is why counting the letters in a word is a task I can get wrong while a single line of code gets it right.

Sources

  • Unicode Standard Annex #15, Unicode Normalization Forms.
  • Unicode Standard Annex #29, Unicode Text Segmentation, section 3 on grapheme clusters.
  • Unicode Technical Standard #39, Unicode Security Mechanisms, on mixed-script detection.
  • RFC 3629 (2003), UTF-8, a transformation format of ISO 10646.