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

Nothing matches. Try truncate, length or ESLint.

Unicode safe strings for JavaScript and TypeScript

Strings, counted the way people see them

characters you seelength(text)

what .length saystext.length

Cut after
whole characters
See every code point in the Text Lab

graphemely counts, slices and truncates JavaScript strings by grapheme cluster, so an emoji, a flag or an accent is never cut in half. About 2 kB, no dependencies.

Terminal
npm install @kwy404/graphemely
Read the API GitHub
Anatomy of one grapheme: the letter e and a combining acute accent, two code points joined by a thread into one character ASCENDER X HEIGHT BASELINE DESCENDER U+0301 COMBINING ACUTE U+0065 LATIN SMALL E ONE CLUSTER CODE POINTS 2 UTF-16 UNITS 2 GRAPHEMES 1
Plate 1. One character on screen, two code points in memory: e and a combining acute accent, tied into one grapheme cluster.

2 kBAbout, gzipped

0Dependencies

14Functions

3ESLint rules

Gem, our cover cat, only ever cuts the yarn between two characters.

The problem

The problem in four lines

JavaScript strings count UTF-16 code units. Emoji, flags and accents take several, so native methods cut them apart.

Native JavaScript
native.js
const family = '\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}';
family.length;             // 8
('Hi' + family).slice(0, 3); // 'Hi\uD83D', broken
'cafe\u{301}'.split('');   // 5 items, accent detached
graphemely
graphemely.js
import { length, slice, graphemes } from '@kwy404/graphemely';
length(family);              // 1
slice('Hi' + family, 0, 3);  // 'Hi' + family
graphemes('cafe\u{301}');    // 4 items

Eight code units. Five code points. One character.

The family emoji above: a man, a woman and a girl joined by zero width joiners.

The Text Lab

Text Lab: native JavaScript against graphemely, live

Type or paste any text, including emoji. Every cluster becomes a tile with its code points, UTF-16 units and bytes, and every operation runs twice: plain JavaScript next to graphemely, with the same build that ships on npm.

Specimens

Graphemeslength(str)

Code points[...str].length

UTF-16 unitsstr.length

UTF-8 bytesTextEncoder

Clusters, one tile each

kept by truncatedroppedwhere native slice cuts

    native cuts here

One import

Every string operation, by visible character

Drop in replacements for the native methods that count UTF-16 code units. Same names, same arguments, the result a person expects.

  • length counts what people see
  • truncate never cuts half an emoji
  • slice and at accept negative indices
  • reverse, padStart and wrap keep characters whole
app.js
import { length, truncate, slice, reverse, wrap } from '@kwy404/graphemely';

const dev = '\u{1F469}\u{1F3FD}\u{200D}\u{1F4BB}'; // technologist
const title = `Launch day ${dev} is here`;

title.length;          // 26 UTF-16 code units
length(title);         // 20, what people see
truncate(title, 13);   // 'Launch day ' + dev + '…'
truncate('Launch day is here', 13, { wordBoundary: true });
                       // 'Launch day…'

const flag = '\u{1F1E7}\u{1F1F7}';  // Brazil
slice('Ol\u{E1} ' + flag, -1);      // the flag, whole
reverse('Ol\u{E1} ' + flag);        // flag + ' álO'
wrap('A quick brown fox', 9);       // ['A quick', 'brown fox']

How it works

Segment first, then count and cut

  1. Step 1

    A thread of code points with dashed outlines around each grapheme cluster UAX #29 BOUNDARIES

    Segment

    Text is split into grapheme clusters with Intl.Segmenter, or a built-in Unicode UAX #29 fallback where it is missing.

  2. Step 2

    Three whole clusters numbered one, two and three 1 2 3 e INDEX BY CLUSTER

    Count and cut

    Lengths and indices refer to clusters, so a flag, a skin tone or an accented letter is always one unit.

  3. Step 3

    A whole emoji on an unbroken thread with a check mark seal WELL FORMED

    Return whole text

    Every result is made of complete characters: no lone surrogates, no detached accents, no half emoji.

A string is not a list of characters. It is a list of UTF-16 code units that sometimes happen to be characters.

The linter

ESLint plugin, running live

Find unsafe string code in an existing project. Edit the file below: the three rules of the plugin run on every keystroke, the same rule code that ships in @kwy404/graphemely/eslint-plugin.

preview.js

Problems

No problems. Every string operation in this file keeps characters whole.

Turn it on

Flat config, ESLint 8.57 or newer. Every rule is a warning in the recommended config.

eslint.config.js
import graphemely from '@kwy404/graphemely/eslint-plugin';

export default [graphemely.configs.recommended];

Index of functions

API

Every function counts in grapheme clusters and throws a TypeError when str is not a string. Full reference with examples in the README.

graphemes(str)string[]

Replaces str.split('') and [...str].

length(str)number

Replaces str.length.

count(str)number

Alias of length that does not shadow anything.

measure(str)Measurement

Graphemes, code points, UTF-16 units and UTF-8 bytes in one call.

slice(str, start?, end?)string

Replaces str.slice and str.substring.

at(str, index)string | undefined

Replaces str.at and str[i].

splitAt(str, index)[string, string]

Replaces two slices.

truncate(str, max, options?)string

Replaces str.slice(0, n) + '...'. Options: ellipsis, wordBoundary, position (end, start or middle).

reverse(str)string

Replaces str.split('').reverse().join('').

padStart(str, n, pad?)string

Replaces str.padStart.

padEnd(str, n, pad?)string

Replaces str.padEnd.

wrap(str, width, options?)string[]

Replaces hand written word wrap. Option: hard.

isWellFormed(str)boolean

The ES2024 method, everywhere.

toWellFormed(str)string

The ES2024 method, everywhere.

Install

Install and import

ESM and CommonJS, TypeScript types included. Works in Node 16 and newer, every modern browser, Deno and Bun.

Install

Terminal
npm install @kwy404/graphemely

Import

Import only what you use; everything is tree shakeable.

index.js
import { truncate, length, slice, reverse } from '@kwy404/graphemely';
// CommonJS
const { truncate } = require('@kwy404/graphemely');
// Deno
import { truncate } from 'npm:@kwy404/graphemely';

Letters to the editor

Questions

What is a grapheme cluster?

The Unicode name for a character as a person sees it: one or more code points shown as a single unit, such as a letter with an accent, a flag or an emoji with a skin tone.

Why does an emoji have length 2 in JavaScript?

JavaScript strings are UTF-16. Most emoji live outside the Basic Multilingual Plane and take a surrogate pair of two code units, and .length counts code units. Sequences such as families and flags take even more.

How is graphemely different from Intl.Segmenter?

graphemely uses Intl.Segmenter when it exists and adds the operations you actually need on top of it: length, slice, at, truncate with ellipsis and word boundaries, reverse, pad and wrap, plus a Unicode fallback for runtimes without it.

Does truncate count the ellipsis?

Yes. truncate(str, 10) returns at most 10 visible characters including the ellipsis, so the result always fits the space you have.

Does it work with TypeScript, CommonJS, Deno and Bun?

Yes. The package ships ESM and CommonJS builds with TypeScript types, has zero dependencies and runs in Node 16 and newer, every modern browser, Deno and Bun.