JavaScript · Unicode Segmentation

Unicode Segmentation

import { Utf8Segments } from 'stringzilla';import { Utf8SegmentsConstructor } from 'stringzilla'; 6.0.0-rc.1 · cb8d956a

Ask your coding agent about this page, or add the docs server to it

curl -s 'https://www.unum.cloud/docs/stringzilla/javascript/unicode-segmentation.md' | claude -p "How would this fit my code?"

Four iterable classes lazily split a UTF-8 buffer into TR29 and UAX14 segments: Utf8Wordbreaks for words, Utf8Graphemes for grapheme clusters, Utf8Sentences for sentences, and Utf8Linebreaks for line-break opportunities. Each is constructed with the source buffer and an optional validate flag, and is its own iterator, yielding zero-copy subarray views into the buffer it keeps alive.

const words = [...new sz.Utf8Wordbreaks(Buffer.from("Hello world!"))].map((b) => b.toString());
assert.deepStrictEqual(words, ["Hello", " ", "world", "!"]);

const graphemes = [...new sz.Utf8Graphemes(Buffer.from("a👩‍👩‍👧‍👦b"))].map((b) => b.toString());
assert.deepStrictEqual(graphemes, ["a", "👩‍👩‍👧‍👦", "b"]); // the ZWJ family is one cluster

API

InterfaceUtf8SegmentsIterator over segments of a UTF-8 buffer, as zero-copy subarray views of the buffer it keeps alive.1
stringzilla.d.ts:127 ↗
interface Utf8Segments extends Iterable<Buffer>
nextThe next segment, or done once the buffer is exhausted.
stringzilla.d.ts:129 ↗
next(): IteratorResult<Buffer, undefined>
InterfaceUtf8SegmentsConstructorConstructs a segment iterator over a UTF-8 buffer.1
stringzilla.d.ts:136 ↗
interface Utf8SegmentsConstructor
Utf8SegmentsConstructor
stringzilla.d.ts:141 ↗
new Utf8SegmentsConstructor(
    buffer: Buffer,
    validate?: boolean,
): Utf8Segments

Parameters

bufferBufferUTF-8 encoded input
validatebooleanIf true, validates UTF-8 and throws on invalid input