length Counts UTF-16 Units Not Characters
Measure and index strings by UTF-16 code units: length and bracket access split astral emoji into surrogates, while spread iteration reads whole code points.
Code
const labels = ["café", "éclair", "🏠", "👍🏽", "a"];
for (const s of labels) {
console.log(JSON.stringify(s), "units:", s.length, "code points:", [...s].length);
}
console.log("👍".length, [..."👍"].length);
// 索引访问按码元切:增补字符被劈成代理对
console.log("🏠"[0].codePointAt(0).toString(16), "🏠".codePointAt(0).toString(16));
// codePointAt 读取完整码点,即使起点落在低位
const emoji = "👍🏽";
console.log(emoji.codePointAt(0).toString(16), emoji.codePointAt(2).toString(16));
// for...of 按码点迭代,不会被代理对劈开
for (const ch of emoji) console.log(ch, ch.codePointAt(0).toString(16));Output
Captured from a sandboxed run of this snippet in the build pipeline.
"café" units: 4 code points: 4
"éclair" units: 6 code points: 6
"🏠" units: 2 code points: 1
"👍🏽" units: 4 code points: 2
"a" units: 1 code points: 1
2 1
d83c 1f3e0
1f44d 1f3fd
👍 1f44d
🏽 1f3fdHow it works
The core work runs in nested loops — outer for (const s of labels), inner for (const ch of emoji) console.log(ch, ch.codePointAt(0).toString(16));.
Demo state sits in top-level bindings: labels, emoji.
Watch out for
- No package installation, no environment variables, no setup steps.
Using it
Output lines are prefixed (👍, 🏠), so the outcome of each step lands visibly on its own printed line.
Key statements
const labels = ["café", "éclair", "🏠", "👍🏽", "a"];
const emoji = "👍🏽";
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `labels`, `emoji`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.