What is a Unicode surrogate, and why might it appear in a programming-language string?
Quick answer
A Unicode surrogate is one of two UTF-16 code units used together to represent a code point outside the Basic Multilingual Plane. In JavaScript, string indexes and length count those 16-bit units, so one such code point can take two indexes even though it is one code point. Iteration can expose code points, but that still does not necessarily count visual grapheme clusters. Other languages may use different string models. [S1]
The question, the details, the next step.
A practical checklist
Name the environment before applying JavaScript’s UTF-16 explanation.
Decide whether you need a code-unit index, a code-point count, or a visual grapheme count.
For JavaScript, compare
lengthwith string iteration when investigating a supplementary code point.When inspecting a suspicious unit, check whether it has a matching surrogate partner.
In bug reports, include the operation, the measurement used, and a minimal example.
A few more useful answers
Does a JavaScript string length of 2 always mean there is one supplementary code point?
No. length counts UTF-16 code units, not code points, so the number alone does not tell you how those units are grouped. Inspect the string and the operation you are using.
Does iterating a JavaScript string count what a person sees as one character?
Not necessarily. The string iterator yields code points, but code points do not necessarily correspond one-to-one with visual grapheme clusters. [S1]
Do surrogate pairs explain string indexing in every programming language?
No. The cited behavior describes JavaScript’s UTF-16 strings, indexes, and length; it does not establish the string model used by other languages. [S1]
Sources
References used for this guide.
- [S1] JavaScript String: UTF-16 code units, surrogate pairs, and indexing developer.mozilla.org · Checked
