Why can text length differ between bytes, code points, and visible characters?
Quick answer
Text length depends on what you count. Bytes measure encoded storage, code points count Unicode values, and user-perceived characters approximate the units a person sees or edits. For e + a combining acute accent + 🙂, UTF-8 uses 7 bytes, there are 3 code points, and there are about 2 visible characters. State the encoding and counting method whenever a length limit matters.
The question, the details, the next step.
A practical checklist
Identify whether the question concerns storage, Unicode values, or user-facing characters.
Name the encoding when reporting bytes, such as UTF-8.
Check whether a stated limit counts bytes, code points, grapheme clusters, or another measure.
For JavaScript, do not treat
string.lengthas a visible-character count.Show the exact sample text and label each reported count.
A few more useful answers
Can a visible character contain more than one code point?
Yes. A base letter followed by a combining mark can form one user-perceived unit while containing multiple code points. [S1]
Is a visible-character count always objectively fixed?
Not as a universal measure. User-perceived units depend on the text and operation, so specify the counting method when precision matters. [S1]
Does JavaScript `string.length` count UTF-8 bytes?
No. JavaScript string length is based on UTF-16 code units; it is not a UTF-8 byte count or a user-perceived-character count. [S2]
Sources
References used for this guide.
- [S1] W3C: Character encodings and user-perceived characters w3.org · Checked
- [S2] MDN: JavaScript strings, UTF-16 code units, code points, and grapheme clusters developer.mozilla.org · Checked
