JavaScript · Unicode Segmentation

Unicode Segmentation

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

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:123 ↗
interface Utf8Segments extends Iterable<Buffer>
nextThe next segment, or done once the buffer is exhausted.
stringzilla.d.ts:125 ↗
next(): IteratorResult<Buffer, undefined>
InterfaceUtf8SegmentsConstructorConstructs a segment iterator over a UTF-8 buffer.1
stringzilla.d.ts:132 ↗
interface Utf8SegmentsConstructor
Utf8SegmentsConstructor
stringzilla.d.ts:137 ↗
new Utf8SegmentsConstructor(
    buffer: Buffer,
    validate?: boolean,
): Utf8Segments

Parameters

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