FstringWidth
Bun

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 is useful for:

  • Aligning text in a terminal
  • Quickly checking if a string contains ANSI escape codes
  • Measuring the width of a string in a terminal

This API is designed to match the popular "string-width" package, so that existing code can be easily ported to Bun and vice versa.

@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

    When it's ambiugous and true, count emoji as 1 characters wide. If false, emoji are counted as 2 character wide.

  • countAnsiEscapeCodes?: boolean

    If true, count ANSI escape codes as part of the string width. If false, ANSI escape codes are ignored when calculating the string width.