string-width

repository·main·Indexed 19 days ago

https://github.com/sindresorhus/string-width

A 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.

Tokens
747
Snippets
5
Records
6
Agent score
18%

What's inside string-width

  1. Use stringWidth to measure visual string width

    main

    Import 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');
    //=> 2
  2. Configure stringWidth options

    main

    You can pass an options object to stringWidth to control how specific character types are handled.

    OptionTypeDefaultDescription
    ambiguousIsNarrowbooleantrueIf true, counts ambiguous width characters as narrow (1). If false, counts them as wide (2).
    countAnsiEscapeCodesbooleanfalseIf true, ANSI escape codes are included in the width calculation instead of being stripped.
  3. Calculate visual string width with `stringWidth()`

    main

    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:

    • Emoji: RGI emoji clusters and ZWJ sequences are treated as double-width.
    • Hangul: Modern Hangul L+V(+T) syllables are collapsed to a width of 2.
    • ANSI: ANSI escape codes are stripped before calculation unless countAnsiEscapeCodes is set to true.
    • Tabs: Tabs are ignored by design.
    import stringWidth from 'string-width';
    
    stringWidth('hello'); // 5
    stringWidth('🥮'); // 2
  4. Use stringWidth() to get visual string width

    main

    The 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