Install string-width via npm
mainInstall the string-width package using npm to measure the visual width (number of columns) of a string, accounting for fullwidth Unicode characters and stripping ANSI escape codes.
npm install string-widthrepository·main·Indexed 19 days ago
https://github.com/sindresorhus/string-widthA utility for determining the visual width of a string in terms of terminal columns. It handles fullwidth Unicode characters, emoji clusters, and Hangul syllables, while ignoring ANSI escape codes by default. Version 8.2.2.
Install the string-width package using npm to measure the visual width (number of columns) of a string, accounting for fullwidth Unicode characters and stripping ANSI escape codes.
npm install string-widthImport stringWidth to calculate how many columns a string occupies. It correctly handles fullwidth characters (counting them as 2) and ignores ANSI escape codes by default.
import stringWidth from 'string-width';
stringWidth('a');
//=> 1
stringWidth('古');
//=> 2
stringWidth('\u001B[1m古\u001B[22m');
//=> 2The primary API for calculating the visual width of a string.
Parameters:
string (string): The string to be measured.options (object): Configuration options to modify width calculation behavior.stringWidth(string, options?)You can pass an options object to stringWidth to control how specific character types are handled.
| Option | Type | Default | Description |
|---|---|---|---|
ambiguousIsNarrow | boolean | true | If true, counts ambiguous width characters as narrow (1). If false, counts them as wide (2). |
countAnsiEscapeCodes | boolean | false | If true, ANSI escape codes are included in the width calculation instead of being stripped. |
The stringWidth function calculates the visual width of a string, accounting for how characters are rendered in terminals. It handles complex cases like emoji clusters, Hangul syllables, and East Asian width rules.
By default, it ignores ANSI escape codes and treats 'ambiguous' characters as narrow. You can configure these behaviors via the options object.
Key behaviors:
countAnsiEscapeCodes is set to true.import stringWidth from 'string-width';
stringWidth('hello'); // 5
stringWidth('🥮'); // 2The stringWidth function calculates the visual width of a string, representing the number of columns required to display it. It correctly handles fullwidth Unicode characters (which count as 2) and ignores ANSI escape codes by default.
Returns a number representing the column count.
import stringWidth from 'string-width';
stringWidth('a');
//=> 1
stringWidth('古');
//=> 2
stringWidth('\u001B[1m古\u001B[22m');
//=> 2