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. 03 Split

Splitting text into characters

The split('') method gives you UTF-16 code units and [...str] gives you code points. Neither matches what a person calls a character. graphemes(str) from graphemely splits into grapheme clusters.

Code points threaded like beads on a string of yarn, grouped into four clusters: c, a, f and e with its combining accent c U+0063 a U+0061 f U+0066 e U+0065 U+0301 GRAPHEMES(STR)4 CLUSTERS5 CODE POINTS
Plate 4. Code points threaded like beads: graphemes(str) only cuts the thread between clusters.

The fix, copy and paste

example.js
import { graphemes } from '@kwy404/graphemely';

graphemes('abc');                         // ['a', 'b', 'c']
graphemes('cafe\u{301}');                 // ['c', 'a', 'f', 'e\u{301}']
graphemes('\u{1F44D}\u{1F3FD}!');         // ['\u{1F44D}\u{1F3FD}', '!'], skin tone kept
graphemes('\u{D55C}\u{AE00}');            // 2 Hangul syllables
graphemes('a\r\nb');                      // ['a', '\r\n', 'b']

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.

Three ways to split, compared

MethodUnitThumbs up with a skin tone becomes
str.split('')UTF-16 code unit4 broken pieces (lone surrogates)
[...str], Array.from(str)Code point2 pieces: thumbs up, then a lone skin tone swatch
graphemes(str)Grapheme cluster1 piece, exactly as displayed

Using Intl.Segmenter directly

Modern runtimes include Intl.Segmenter, and graphemely uses it when it is there. The direct version is:

example.js
const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
const chars = Array.from(segmenter.segment(str), (s) => s.segment);

graphemely adds a fast path for plain ASCII and Latin-1 text, a built-in fallback for runtimes without Intl.Segmenter, and the operations you usually need next: truncate, slice, reverse, pad and wrap.

A character is whatever a person would point at with a finger.

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. 04Lone surrogatesFind and repair the broken halves of emoji.