Get the visual width of a string - the number of columns required to display it
by sindresorhusJavaScript
Last 12 weeks · 3 commits
4 of 6 standards met
Fixes #62 Replaces with the built-in , following up on the earlier attempts in #61 by @RobinTail and #73 by @dulmandakh, which were blocked because mishandled OSC 8 hyperlinks at the time. That was fixed in nodejs/node#54865 and shipped in Node.js 22.10.0, so engines is bumped to rather than plain to keep v22.0 through v22.9 from silently getting the old behavior. Node.js 20 is dropped from the CI matrix to match. I checked the output of both functions against CSI sequences and OSC 8 hyperlinks (BEL and ST terminated) and they match exactly, and the existing hyperlink test in test.js covers the regression case. All 224 tests pass. Happy to adjust the engines range or split out the CI matrix change if you'd prefer to handle those separately.
At the moment, spacing marks () characters are considered zero-width while they are combining but spacing and occupying horizontal space. They should not be considered zero-width given their nature. Related: https://github.com/sindresorhus/string-width/issues/6, https://github.com/prettier/prettier/issues/19535, https://github.com/oxc-project/oxc/issues/23863#issuecomment-4881454798
In my terminal (Terminal.app), I can write the string: Which consists of 6 instances of the code point (a Korean character), as a single grapheme cluster. In my terminal, each code point takes up 2 columns visually, for a total of 12 columns. But reports the entire string as just being 2 columns wide. This seems like a bug. I looked at the source code, and the culprit seems to be here: https://github.com/sindresorhus/string-width/blob/main/index.js#L111 , where it's just looking at the first code point of the grapheme cluster, rather than counting all of them.
Repository: sindresorhus/string-width. Description: Get the visual width of a string - the number of columns required to display it Stars: 529, Forks: 44. Primary language: JavaScript. Languages: JavaScript (98.7%), TypeScript (1.3%). License: MIT. Latest release: v8.2.2 (1mo ago). Open PRs: 1, open issues: 1. Last activity: 1mo ago. Community health: 85%. Top contributors: sindresorhus, fisker, coreyfarrell, BendingBender, adam2k, TheAlexLichter, privatenumber, LitoMore, Richienb, seachicken and others.