Unicode safe strings for JavaScript and TypeScript
Strings, counted the way people see them
characters you seelength(text)
what .length saystext.length
whole characters
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.
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.
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
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 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
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.
lengthcounts what people seetruncatenever cuts half an emojisliceandataccept negative indicesreverse,padStartandwrapkeep characters whole
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
-
Step 1
Segment
Text is split into grapheme clusters with
Intl.Segmenter, or a built-in Unicode UAX #29 fallback where it is missing. -
Step 2
Count and cut
Lengths and indices refer to clusters, so a flag, a skin tone or an accented letter is always one unit.
-
Step 3
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.
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.
- no-unsafe-string-split reports
str.split('') - no-unsafe-reverse reports
str.split('').reverse()and[...str].reverse().join('') - prefer-graphemely-truncate reports
str.slice(0, n) + '...'
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
npm install @kwy404/graphemely
pnpm add @kwy404/graphemely
yarn add @kwy404/graphemely
bun add @kwy404/graphemely
Import
Import only what you use; everything is tree shakeable.
import { truncate, length, slice, reverse } from '@kwy404/graphemely';
// CommonJS
const { truncate } = require('@kwy404/graphemely');
// Deno
import { truncate } from 'npm:@kwy404/graphemely';
Guides
Fix the common string bugs
Four short guides: what goes wrong, why, and the fix to copy and paste.
- 01Truncating textShorten text to a length with an ellipsis, never half a character.
- 02Counting charactersWhy an emoji can have a length of 2, and how to count what people see.
- 03Splitting text into charactersVisible characters instead of code units or code points.
- 04Lone surrogatesFind and repair the broken halves of emoji.
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.