JavaScript Length Lies: Why 'π¨βπ©βπ§βπ¦' Counts as 11 and Your Han Regex Is Missing Half of China
Character counting in JavaScript is full of silent traps: .length counts UTF-16 code units, common Han regexes miss entire Unicode blocks, and property escapes fail without the u flag. These bugs can reject valid submissions, allow padding, and blow past title limits, all without a single error message.
A JavaScript word-count script used a hanzi regex of \u4e00-\u9fff, which only covers the CJK Basic block. When the script encountered an article padded with 200 characters from Extension B (like π ), it counted 1000 instead of 1200 and failed the gate. The same regex also misses symbols like β and fullwidth letters, which look like Chinese but aren't counted.
Measuring 14 samples with four counting methods shows the gap between .length, code points, graphemes, and Han matches. An emoji family sequence .length=11 but only 1 grapheme; a heart with variation selector is 2 code units; NFC and NFD forms of Γ© have different lengths. Title truncation platforms use .length, so a title with one emoji eats 10 extra code units, pushing it past the limit.
The fix uses Intl.Segmenter for grapheme count, .length for truncation, and \p{Script=Han} with the u flag for Han characters. The u flag is criticalβwithout it, the regex silently matches literal text instead of erroring, a trap that's easy to miss.
The silent failure of a missing u flag on property escapes is worse than an exception, because the regex matches literal text and produces false results without any warning.
CJK Extension blocks are poorly represented in common JavaScript regexes, yet they appear in real names, place names, and historical textsβrelying on the basic block alone is a correctness risk.
The same problem applies to any language using combining characters or non-BMP symbols; a character-count UI that naively uses .length will mislead users.
The gap between .length and grapheme count is not an edge case for emoji; it directly impacts title limits and content gates, where a few extra characters can block a publication.
Character counting is a domain where JavaScript's Unicode model forces developers to make a deliberate choice per use case, and mixing them up leads to errors of the scale "1200 vs 1000".