string-width
Advanced tools
Comparing version 5.0.1 to 5.1.0
@@ -0,1 +1,10 @@ | ||
export interface Options { | ||
/** | ||
Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). | ||
@default false | ||
*/ | ||
readonly ambiguousIsNarrow: boolean; | ||
} | ||
/** | ||
@@ -20,2 +29,2 @@ Get the visual width of a string - the number of columns required to display it. | ||
*/ | ||
export default function stringWidth(string: string): number; | ||
export default function stringWidth(string: string, options?: Options): number; |
21
index.js
import stripAnsi from 'strip-ansi'; | ||
import isFullwidthCodePoint from 'is-fullwidth-code-point'; | ||
import eastAsianWidth from 'eastasianwidth'; | ||
import emojiRegex from 'emoji-regex'; | ||
export default function stringWidth(string) { | ||
export default function stringWidth(string, options = {}) { | ||
if (typeof string !== 'string' || string.length === 0) { | ||
@@ -18,2 +18,3 @@ return 0; | ||
const ambiguousCharWidth = options.ambiguousIsNarrow ? 1 : 2; | ||
let width = 0; | ||
@@ -34,8 +35,14 @@ | ||
// Surrogates | ||
if (codePoint > 0xFFFF) { | ||
index++; | ||
const code = eastAsianWidth.eastAsianWidth(string.charAt(index)); | ||
switch (code) { | ||
case 'F': | ||
case 'W': | ||
width += 2; | ||
break; | ||
case 'A': | ||
width += ambiguousCharWidth; | ||
break; | ||
default: | ||
width += 1; | ||
} | ||
width += isFullwidthCodePoint(codePoint) ? 2 : 1; | ||
} | ||
@@ -42,0 +49,0 @@ |
{ | ||
"name": "string-width", | ||
"version": "5.0.1", | ||
"version": "5.1.0", | ||
"description": "Get the visual width of a string - the number of columns required to display it", | ||
@@ -50,4 +50,4 @@ "license": "MIT", | ||
"dependencies": { | ||
"eastasianwidth": "^0.2.0", | ||
"emoji-regex": "^9.2.2", | ||
"is-fullwidth-code-point": "^4.0.0", | ||
"strip-ansi": "^7.0.1" | ||
@@ -54,0 +54,0 @@ }, |
@@ -30,2 +30,23 @@ # string-width | ||
## API | ||
### stringWidth(string, options?) | ||
#### string | ||
Type: `string` | ||
The string to be counted. | ||
#### options | ||
Type: `object` | ||
##### ambiguousIsNarrow | ||
Type: `boolean`\ | ||
Default: `false` | ||
Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). | ||
## Related | ||
@@ -32,0 +53,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
5746
61
68
+ Addedeastasianwidth@^0.2.0
+ Addedeastasianwidth@0.2.0(transitive)
- Removedis-fullwidth-code-point@^4.0.0
- Removedis-fullwidth-code-point@4.0.0(transitive)