1 | 'use strict';
|
2 | const stripAnsi = require('strip-ansi');
|
3 | const isFullwidthCodePoint = require('is-fullwidth-code-point');
|
4 | const emojiRegex = require('emoji-regex');
|
5 |
|
6 | const stringWidth = string => {
|
7 | string = string.replace(emojiRegex(), ' ');
|
8 |
|
9 | if (typeof string !== 'string' || string.length === 0) {
|
10 | return 0;
|
11 | }
|
12 |
|
13 | string = stripAnsi(string);
|
14 |
|
15 | let width = 0;
|
16 |
|
17 | for (let i = 0; i < string.length; i++) {
|
18 | const code = string.codePointAt(i);
|
19 |
|
20 |
|
21 | if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
|
22 | continue;
|
23 | }
|
24 |
|
25 |
|
26 | if (code >= 0x300 && code <= 0x36F) {
|
27 | continue;
|
28 | }
|
29 |
|
30 |
|
31 | if (code > 0xFFFF) {
|
32 | i++;
|
33 | }
|
34 |
|
35 | width += isFullwidthCodePoint(code) ? 2 : 1;
|
36 | }
|
37 |
|
38 | return width;
|
39 | };
|
40 |
|
41 | module.exports = stringWidth;
|
42 |
|
43 | module.exports.default = stringWidth;
|