Vol. 1.1.0 A field guide to Unicode safe strings in JavaScript npm i @kwy404/graphemely

Nothing matches. Try truncate, length or ESLint.

Guide No. 04 Surrogates

Lone surrogates

A lone surrogate is half of an emoji (or any character outside the Basic Multilingual Plane) left behind when a string is cut by code unit. Detect it with isWellFormed(str) and replace it with U+FFFD using toWellFormed(str).

An emoji torn into its two UTF-16 halves, a high and a low surrogate, and the replacement character that repairs it \uD83D\uDE00 ? U+FFFDTOWELLFORMED ONE EMOJI, TWO HALVES
Plate 6. One emoji torn into its two UTF-16 halves, and the replacement character that repairs it.

The fix, copy and paste

example.js
import { isWellFormed, toWellFormed } from '@kwy404/graphemely';

const broken = '\u{1F600}'.slice(0, 1);   // '\uD83D'
isWellFormed(broken);                    // false
toWellFormed('ok' + broken);             // 'ok\u{FFFD}'
encodeURIComponent(toWellFormed(broken)); // '%EF%BF%BD', no URIError

Emoji in the code samples are written as JavaScript escapes, for example \u{1F468} for a man. In your own code you can type the emoji directly.

Why lone surrogates are a problem

  • encodeURIComponent throws URIError: URI malformed.
  • TextEncoder and most UTF-8 encoders silently replace them with U+FFFD, so data changes on its way to a server.
  • Some APIs and databases reject the request as invalid UTF-8.
  • They render as a replacement box or a question mark in a diamond.

Where they come from

Almost always from cutting text with code unit indices: str.slice(0, n), str.substring, str[i], str.split('') or a maximum length enforced by an input field. The real fix is to cut by grapheme cluster with truncate or slice, so they never appear. toWellFormed is the safety net for data that is already broken.

Native methods

ES2024 added String.prototype.isWellFormed and toWellFormed. They are missing on Node 18 and older browsers. The graphemely versions behave the same and work everywhere.

Half an emoji is not a smaller emoji. It is invalid text.

Install

Terminal
npm install @kwy404/graphemely

Works in Node 16 and newer, all modern browsers, Deno and Bun. ESM and CommonJS, TypeScript types included, zero dependencies, about 2 kB gzipped. Try your own text in the Text Lab.

  1. 01Truncating textShorten text to a length with an ellipsis, never half a character.
  2. 02Counting charactersWhy an emoji can have a length of 2, and how to count what people see.
  3. 03Splitting text into charactersVisible characters instead of code units or code points.