Accurate displayed string width with grapheme-aware Unicode handling
npm install string-width-modernAccurate displayed string width for modern Unicode. Grapheme‑aware, handles emojis, full‑width CJK, surrogate pairs, combining marks, and ZWJ sequences. Zero runtime dependencies.
``bash`
npm install string-width-modern
`ts
import stringWidth from 'string-width-modern';
stringWidth('hello'); // 5
stringWidth('こんにちは'); // 10
stringWidth('🙂'); // 2
stringWidth('e\u0301'); // 1
stringWidth('👨👩👧👦'); // 2
stringWidth('🇺🇸'); // 2
`
`js`
const stringWidth = require('string-width-modern');
console.log(stringWidth('✌️'));
- Uses Intl.Segmenter to iterate grapheme clusters and Unicode property escapes for categorization.
- Treats CJK scripts and Fullwidth Forms as width 2.
- Treats emoji (including ZWJ, variation selectors, skin tones, flags) as width 2.
- Combines marks are width 0 when standalone and do not increase cluster width.
- ✌ vs ✌️: without U+FE0F variation selector is width 1; with it is width 2.U+0301
- Standalone combining mark is width 0; e\u0301 is width 1.🇯🇵
- Regional indicator pairs (e.g., ) are width 2.
`ts`
function stringWidth(input: string): number
- ESM + CJS via tsup`
- Type definitions included
MIT