Get the visual width of a string - the number of columns required to display it
by sindresorhusJavaScript
Last 12 weeks ยท 6 commits
4 of 6 standards met
strip-ansi has below note on its npm page. So this PR removes strip-ansi dependency to use node:util. [!NOTE] Node.js has this built-in now with stripVTControlCharacters. The benefit of this package is consistent behavior across Node.js versions and faster improvements. The Node.js version is actually based on this package.
Repository: sindresorhus/string-width. Description: Get the visual width of a string - the number of columns required to display it Stars: 522, Forks: 39. Primary language: JavaScript. Languages: JavaScript (98.3%), TypeScript (1.7%). License: MIT. Latest release: v8.2.0 (2w ago). Open PRs: 0, open issues: 1. Last activity: 2w ago. Community health: 85%. Top contributors: sindresorhus, fisker, coreyfarrell, BendingBender, adam2k, privatenumber, LitoMore, Richienb, seachicken, shinnn and others.
String width calculation is a hot path in terminal rendering โ it's called on every line of output in tools like Ink, cli-truncate, wrap-ansi, and log-update. With the growth of AI-powered terminal agents that stream large amounts of text, this is becoming even more performance-sensitive. I profiled string-width and found two low-hanging optimizations: runs unconditionally even when no ANSI codes are present, and runs on every call even for pure ASCII input where width = length. ASCII + ANSI benchmarks (Apple M2 Max, Node 25.2.1) Non-ASCII inputs (CJK, emoji, mixed) are unaffected โ they fall through to the existing path. PRs https://github.com/sindresorhus/string-width/pull/72 โ ASCII fast path + stripAnsi guard https://github.com/chalk/strip-ansi/pull/54 โ adds fast path to strip-ansi https://github.com/sindresorhus/get-east-asian-width/pull/14 โ packed arrays with binary search (3.5x faster, -25% bundle size) Optimizations 1. ASCII fast path โ regex detects pure printable ASCII, returns directly. Skips , regex, and EAW lookup entirely. 61x faster for short ASCII, the most common input type. 2. stripAnsi guard โ check before calling . Avoids the overhead of strip-ansi's regex on strings that contain no ANSI escapes. 14x faster for ANSI-free short strings.
Problem and run on every call regardless of input. For ASCII strings like , the segmenter alone costs ~4ยตs โ but width = length. Changes ASCII fast path Regex check to detect pure printable ASCII โ skip segmenter/regex/EAW entirely stripAnsi guard Skip when no ESC () or CSI () present Performance (Apple M2 Max, Node 25.2.1) Non-ASCII inputs (CJK, emoji, mixed) are unaffected โ they fall through to the existing path. All 198 tests pass. Upstream https://github.com/chalk/strip-ansi/pull/54 https://github.com/sindresorhus/get-east-asian-width/pull/14 Ref: https://github.com/sindresorhus/string-width/issues/71