Skip to content
jshacks.dev
Fundamentals

JavaScript Strings Are UTF 16 and What That Breaks

JavaScript strings are sequences of UTF-16 code units, so an emoji has length 2 and slicing can split it. See what breaks and the safe ways to count and cut.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite and npm logos.

A user types a display name of 20 emoji into a field limited to 20 characters, and the form says it is too long. Another truncates a string at 100 characters and ends it with a broken box where a face used to be. A third reverses a string and returns garbage. All three are the same cause: JavaScript strings are sequences of UTF-16 code units, and a code unit is not a character. This post shows what length and indexing really count, the three levels at which a string can be split, and the tools to cut and count at the level you mean. It runs on Node.js 24. The full coverage of Unicode, including normalization, is in the Unicode post, and the type sits among the seven primitives.

Three ways to count one string

The same string has a different length depending on what you count.

JavaScript
const samples = ["a", "Γ©", "é", "πŸ˜€", "πŸ‘¨β€πŸ‘©β€πŸ‘§"];

const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });

for (const text of samples) {
  const units = text.length;
  const codePoints = [...text].length;
  const graphemes = [...segmenter.segment(text)].length;
  const bytes = new TextEncoder().encode(text).length;
  console.log(JSON.stringify(text), units, codePoints, graphemes, bytes);
}
Text
"a" 1 1 1 1
"Γ©" 1 1 1 2
"é" 2 2 1 3
"πŸ˜€" 2 1 1 4
"πŸ‘¨β€πŸ‘©β€πŸ‘§" 8 5 1 18

The columns are code units, code points, graphemes and UTF-8 bytes. The third row is e followed by a combining acute accent, which displays as one letter but is two code points. The emoji takes two code units because its code point is above U+FFFF, and the family sequence is three emoji joined by two invisible joiners: five code points, eight code units, one thing a reader sees. length reports the first number only.

Surrogate pairs

UTF-16 stores a code point above U+FFFF as two units, a high surrogate followed by a low one. Each unit alone is not a character, and string methods that work by index can separate them.

JavaScript
const face = "πŸ˜€";

console.log(face.length);
console.log(face.charCodeAt(0).toString(16));
console.log(face.charCodeAt(1).toString(16));
console.log(face.codePointAt(0).toString(16));
console.log(JSON.stringify(face.slice(0, 1)));
console.log(JSON.stringify(face.split("")));
console.log("aπŸ˜€b".split("").reverse().join("") === "bπŸ˜€a");
console.log([..."aπŸ˜€b"].reverse().join(""));
Text
2
d83d
de00
1f600
"\ud83d"
["\ud83d","\ude00"]
false
bπŸ˜€a

charCodeAt() returns the individual units, and codePointAt() combines the pair into the real code point U+1F600. Slicing at index 1 left a lone high surrogate, which prints as the escape in the output and as a replacement box in a terminal. Reversing with split("") flips the order of the pair and breaks the character, and spreading the string first iterates by code point and reverses correctly.

for...of, spread, Array.from() and Array.prototype.entries() on a spread string all use the string iterator, which yields code points. That one change fixes most surrogate bugs, and it is why the spread form is the default we reach for. Note that String.prototype.at() and indexing still work on units, as covered in the at() post.

Detecting and repairing broken strings

A lone surrogate is not valid Unicode text. It cannot be encoded as UTF-8, so APIs that encode or send text may replace it, reject it or throw. Two methods, available since Node.js 20, test and fix this.

JavaScript
const broken = "ok" + "πŸ˜€".slice(0, 1);

console.log(broken.isWellFormed());
console.log("okπŸ˜€".isWellFormed());
console.log(JSON.stringify(broken.toWellFormed()));
console.log(new TextEncoder().encode(broken).length);
console.log(encodeURIComponent("okπŸ˜€"));

try {
  encodeURIComponent(broken);
} catch (error) {
  console.log(error.name);
}
Text
false
true
"okοΏ½"
5
ok%F0%9F%98%80
URIError

toWellFormed() replaces each lone surrogate with the replacement character U+FFFD. TextEncoder does the same quietly, giving five bytes, two for ok and three for the encoded replacement. encodeURIComponent() refuses, with a URIError. If you build strings by slicing, check or repair them before they reach an API.

Cutting text at a safe boundary

The common job is truncation: shorten a title, a summary or a preview to a limit. Cutting by code unit can split a pair, and cutting by code point can split a grapheme. For text that readers see, cut by grapheme.

JavaScript
function truncate(text, limit) {
  const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
  const graphemes = [...segmenter.segment(text)].map((part) => part.segment);
  return graphemes.length <= limit
    ? text
    : graphemes.slice(0, limit).join("") + "…";
}

const text = "ok πŸ‘¨β€πŸ‘©β€πŸ‘§ done";

console.log(text.slice(0, 5));
console.log(truncate(text, 4));
console.log(truncate(text, 20));
Text
ok πŸ‘¨
ok πŸ‘¨β€πŸ‘©β€πŸ‘§β€¦
ok πŸ‘¨β€πŸ‘©β€πŸ‘§ done

The first line is the naive cut, which stopped inside the family sequence and kept only its first member. The second is the grapheme-aware cut, which kept the whole family and added an ellipsis. The third is the untouched string, because it was already within the limit.

The Intl.Segmenter constructor takes a locale and a granularity. Creating one per call, as above, is fine for occasional use, and a shared instance is better for a loop.

Comparing, upper-casing and normalizing

Two strings that look identical can differ at the code point level. A letter with an accent can be one composed code point or a base letter followed by a combining mark, and === treats them as different.

JavaScript
const composed = "Γ©";
const decomposed = "é";

console.log(composed === decomposed);
console.log(composed.normalize("NFC") === decomposed.normalize("NFC"));
console.log("straße".toUpperCase());
console.log("Δ°".toLowerCase().length);
console.log(["z", "Γ€", "a"].sort());
console.log(["z", "Γ€", "a"].sort((a, b) => a.localeCompare(b, "de")));
Text
false
true
STRASSE
2
[ 'a', 'z', 'Γ€' ]
[ 'a', 'Γ€', 'z' ]

normalize("NFC") brings both forms to a canonical one, and comparison then works. Upper-casing ß gives two letters, so a string's length can change under case conversion. Lowercasing the Turkish capital İ gives two code units, a plain i and a combining dot. And the default sort() orders by code unit, which puts À after z. Use localeCompare() or Intl.Collator for text that people read.

What the regular expression engine does

Without the u flag, a regular expression works on code units. With it, on code points.

JavaScript
console.log(/^.$/.test("πŸ˜€"));
console.log(/^.$/u.test("πŸ˜€"));
console.log("πŸ˜€".match(/./g).length);
console.log("πŸ˜€".match(/./gu).length);
console.log(/\p{Emoji_Presentation}/u.test("πŸ˜€"));
Text
false
true
2
1
true

Add u to any pattern that may see characters outside the Basic Multilingual Plane, and it enables \p{...} property escapes. Newer code can use the v flag, which extends that further.

Putting limits on user input

A signup form that limits a display name needs three numbers, and each one has a different job. The visible limit counts graphemes, so a person sees the same count you enforce. The storage limit counts bytes, because the database column is sized in bytes under utf8mb4. And the safety limit caps the code unit count, to bound the work a hostile input can cause.

JavaScript
function checkName(name) {
  const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
  const visible = [...segmenter.segment(name)].length;
  const bytes = new TextEncoder().encode(name).length;
  return { visible, bytes, ok: visible <= 20 && bytes <= 80 && name.length <= 200 };
}

console.log(checkName("Ada Lovelace"));
console.log(checkName("πŸ˜€".repeat(25)));
Text
{ visible: 12, bytes: 12, ok: true }
{ visible: 25, bytes: 100, ok: false }

The second name fails on the visible limit and also on bytes. A name of 20 emoji passes the visible check and uses 80 bytes, exactly at the storage limit, which shows why the byte limit should be set with room for the worst case. Run the checks in the same order everywhere the name is accepted, and put them in one function, so the form, the API and the importer cannot disagree.

A test string worth keeping

Keep one string in your test helpers that exercises every level at once: a plain letter, a composed accent, a decomposed accent, an emoji and a joined family sequence. Run any text-handling function against it, such as truncation, counting, search highlighting and case conversion, and the bugs surface in the first run instead of the first support ticket. The cost is one constant and one extra assertion per function.

Where this advice stops

If your text is ASCII or Latin-1 and always will be, none of this bites, and the unit count equals the character count. The danger is user-generated text, since names, comments and messages contain emoji and accents in any app with real users. Test with a string like "eΜπŸ˜€πŸ‘¨β€πŸ‘©β€πŸ‘§" early, and the surrogate and grapheme bugs surface.

For databases, count bytes and not characters when the column has a byte limit, and use TextEncoder or Buffer.byteLength(), as in the first table. For display widths, such as terminal columns, the count differs again, since wide characters occupy two cells.

JavaScript's string model is defined in the specification under the String type, and MDN documents Intl.Segmenter on its Segmenter reference page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.