grapheme-splitter is a JavaScript library designed to accurately segment strings into user-perceived characters, known as extended grapheme clusters, as defined by Unicode Standard Annex #29 (UAX #29) Default Grapheme Cluster Boundaries. It addresses fundamental issues in JavaScript's native string handling, where `String.length` and simple character iteration can misrepresent visual character counts due to multi-codepoint emojis (e.g., `🏳️🌈`), combining marks (like in German 'ü', Spanish 'ñ', or Hindi text), and 'Zalgo' text. Unlike `String.normalize()` or libraries like `punycode.js`, `grapheme-splitter` provides a comprehensive solution for these complex Unicode cases. The current stable version is 1.0.4, indicating a mature and stable codebase with an infrequent release cadence focused on maintenance rather than rapid feature additions. Its key differentiator is precise adherence to Unicode grapheme cluster rules, making it essential for text processing, input field validation, and display logic in internationalized applications.
npm install grapheme-splitterVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to initialize `GraphemeSplitter` and use its `splitGraphemes` and `countGraphemes` methods across various complex Unicode strings, including multi-codepoint emojis, diacritics, Hindi text, and Zalgo text, showing the correct user-perceived character counts and segments.
Use `new GraphemeSplitter().countGraphemes(myString)` to get the accurate number of user-perceived characters, or `splitGraphemes` for an array of these clusters.
While `String.normalize()` can resolve some canonical equivalences, for full grapheme cluster segmentation, `grapheme-splitter` is required as it implements the UAX #29 standard.
First split the string into an array of grapheme clusters using `splitter.splitGraphemes(myString)`, then slice the resulting array, and finally `join('')` the array back into a string if needed. For example, `splitter.splitGraphemes(myString).slice(0, maxLength).join('')`.Use `const splitter = new GraphemeSplitter(); const correctLength = splitter.countGraphemes(myString);`
Transform the string into an array of grapheme clusters first: `const splitter = new GraphemeSplitter(); const graphemes = splitter.splitGraphemes(myString); const slicedGraphemes = graphemes.slice(0, N); const result = slicedGraphemes.join('');`To iterate over user-perceived characters, use `for (const grapheme of splitter.iterateGraphemes(myString))` or `splitter.splitGraphemes(myString).forEach(...)`.
No dependency data recorded yet.