string-width
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
eastasianwidth | 0.2.0 | 2.83 kB | MIT | prod | |
emoji-regex | 9.2.2 | 10.86 kB | MIT | prod | |
strip-ansi | 7.1.0 | 2.12 kB | MIT | prod |
The string-width npm package provides an effective solution for calculating the visual width of a string, or simply put, the number of columns necessary to display it. This is incredibly useful when dealing with Unicode characters, including fullwidth characters, and command-line output. ANSI escape codes, typically invisible and discounting towards the string's visual length, are automatically stripped off.
Utilizing string-width in your JavaScript project is as easy as installing the package via npm by running npm install string-width
, and then importing and calling the function in your code. Here are some code examples:
// Importing the module
import stringWidth from 'string-width';
// Calculating the visual width of a single character
console.log(stringWidth('a')); // Output: 1
// The visual width of a fullwidth character is 2
console.log(stringWidth('ε€')); // Output: 2
Moreover, string-width allows toggling of certain features via the options parameter:
// Importing the module
import stringWidth from 'string-width';
// Example of using options
console.log(stringWidth('\u001B[1mε€\u001B[22m', {countAnsiEscapeCodes: true})); // Output: 2
In the options object, the ambiguousIsNarrow
option allows you to count ambiguous width characters as narrow or wide, and the countAnsiEscapeCodes
option lets you include ANSI escape codes in the width calculation.
For a comprehensive look at the string-width API and the different options available, please refer to the string-width package page on GitHub. It provides an exhaustive explanation on how to use the module along with the data types, default settings, and other details. For use cases outside of Node.js applications, there is also a command-line interface version available named string-width-cli.