function
stringWidth
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.
The string to measure
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 })); // 13Referenced types
interface StringWidthOptions
- ambiguousIsNarrow?: boolean
If
true, count ambiguous-width characters as 1 character wide. Iffalse, count them as 2 characters wide. - countAnsiEscapeCodes?: boolean
If
true, count ANSI escape codes as part of the string width. Iffalse, ignore them. - perCodePoint?: boolean
If
true, measure every Unicode code point individually (East Asian Width plus emoji presentation, the algorithm Node.js uses forconsole.tableandutil.inspectalignment), so each member of an emoji ZWJ sequence is counted:"π¨βπ©βπ§βπ¦"measures 8. Iffalse, emoji sequences and other grapheme clusters count once:"π¨βπ©βπ§βπ¦"measures 2.