mb-trimwidth
v0.0.5
Published
A module of trim multibyte string by character width. This will work even if contained Unicode, emoji, and surrogate pairs.
Maintainers
Readme
mbTrimWidth
A module of trim multibyte string by character width. This will work even if contained Unicode, emoji, and surrogate pairs.
Requirements
This package uses Intl.Segmenter to correctly count grapheme clusters, including ZWJ emoji sequences (e.g. 👨👩👧👦) and combining characters (e.g. pͪ).
| Environment | Minimum version | |---|---| | Node.js | 16+ | | Chrome | 87+ | | Firefox | 125+ | | Safari | 14.1+ |
[!NOTE]
Intl.Segmenteris not available in older environments. If you need to support them, a polyfill such as@formatjs/intl-segmenteris required.
install
$ npm install --save mb-trimwidthusage
import { mbTrimWidth } from 'mb-trimwidth';
const str1 = 'I love 🏄🌊 and 🏕';
str1.length; // => 18
mbTrimWidth(str1, 9);
// => "I love 🏄🌊"
mbTrimWidth(str1, 9, '…');
// => "I love 🏄…"
const str2 = '🌕の夜は𠮷野屋で𩸽を食べたい😇';
str2.length; // => 19
mbTrimWidth(str2, 9);
// => "🌕の夜は𠮷野屋で𩸽"
mbTrimWidth(str2, 9, '…');
// => "🌕の夜は𠮷野屋で…"Test
import { mbTrimWidth } from 'mb-trimwidth';
const str = 'Lorem ipsum dolor sit amet';
mbTrimWidth(str, 10);
// => "Lorem ipsu"
mbTrimWidth(str, 10, '…');
// => "Lorem ips…"
mbTrimWidth(str, 0);
// => ""
mbTrimWidth(str, 1, '…');
// => "L"
mbTrimWidth(str, 1, '...');
// => "L"
const str = '子もかっこうの「おじぎ猫団」を窓がふみ戸棚ましです。';
mbTrimWidth(str, 12);
// => "子もかっこうの「おじぎ猫"
mbTrimWidth(str, 12, '…');
// => "子もかっこうの「おじぎ…"
const str = 'I love 🏄🌊 and 🏕';
mbTrimWidth(str, 9);
// => "I love 🏄🌊"
mbTrimWidth(str, 9, '…');
// => "I love 🏄…"
const str = '私は🏄🌊と🏕をします';
mbTrimWidth(str, 6);
// => "私は🏄🌊と🏕"
mbTrimWidth(str, 6, '…');
// => "私は🏄🌊と…"
const str = '🌕の夜は𠮷野屋で𩸽を食べたい😇';
mbTrimWidth(str, 9);
// => "🌕の夜は𠮷野屋で𩸽"
mbTrimWidth(str, 9, '…');
// => "🌕の夜は𠮷野屋で…"