function

stringWidth

function stringWidth(
input: string,
): number;

Get the column count of a string as it would be displayed in a terminal. Supports ANSI escape codes, emoji, and wide characters.

This API is designed to match the string-width npm package, so existing code can be ported in either direction.

@param input

The string to measure

@returns

The width of the string in columns

import { stringWidth } from "bun";

console.log(stringWidth("abc")); // 3
console.log(stringWidth("πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦")); // 1
console.log(stringWidth("\u001b[31mhello\u001b[39m")); // 5
console.log(stringWidth("\u001b[31mhello\u001b[39m", { countAnsiEscapeCodes: false })); // 5
console.log(stringWidth("\u001b[31mhello\u001b[39m", { countAnsiEscapeCodes: true })); // 13

Referenced types

interface StringWidthOptions

  • ambiguousIsNarrow?: boolean

    If true, count ambiguous-width characters as 1 character wide. If false, count them as 2 characters wide.

  • countAnsiEscapeCodes?: boolean

    If true, count ANSI escape codes as part of the string width. If false, ignore them.

  • perCodePoint?: boolean

    If true, measure every Unicode code point individually (East Asian Width plus emoji presentation, the algorithm Node.js uses for console.table and util.inspect alignment), so each member of an emoji ZWJ sequence is counted: "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦" measures 8. If false, emoji sequences and other grapheme clusters count once: "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦" measures 2.