stringWidth

Bun

Symbol

stringWidth

function stringWidth(input: string, options?: { ambiguousIsNarrow: boolean; countAnsiEscapeCodes: boolean }): 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