Charts · 19
The four lengths of a string
A username field says “20 characters max” and rejects a 20-letter Vietnamese name. A preview truncates a tweet and leaves half an emoji. A sort puts two identical cafés in different places. All the same bug: a string has four lengths, and .length gives you the one nobody means. Type anything and watch the four counts split apart, then see the three ways to cut it.
One grapheme, four people joined by zero-width joiners: 7 code points, 11 UTF-16 units, 25 bytes.
graphemes1
Intl.Segmenterwhat a person would count, and what backspace deletescode points7
Array.from(s).lengthUnicode scalar values, what a for…of loop yieldsUTF-16 units11
s.lengthwhat .length, .slice and .charAt actually countUTF-8 bytes25
new TextEncoder().encode(s).lengthwhat goes over the wire and into most databases👨👩👧👦U+1F468 U+200D U+1F469 U+200D U+1F467 U+200D U+1F466
The “5 character limit”, three ways
s.slice(0, 5)👨👩
UTF-16 units. Can split a surrogate pair and leave a broken half-character.Array.from(s).slice(0, 5)👨👩👧
Code points. Never splits a pair, still splits a family, a flag or an accent.Intl.Segmenter … slice(0, 5)👨👩👧👦
Graphemes. Cuts where a person would. This is the one to use for a limit.