UNPKG

879 BJavaScriptView Raw
1'use strict';
2const stripAnsi = require('strip-ansi');
3const isFullwidthCodePoint = require('is-fullwidth-code-point');
4const emojiRegex = require('emoji-regex');
5
6const 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 // Ignore control characters
21 if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
22 continue;
23 }
24
25 // Ignore combining characters
26 if (code >= 0x300 && code <= 0x36F) {
27 continue;
28 }
29
30 // Surrogates
31 if (code > 0xFFFF) {
32 i++;
33 }
34
35 width += isFullwidthCodePoint(code) ? 2 : 1;
36 }
37
38 return width;
39};
40
41module.exports = stringWidth;
42// TODO: remove this in the next major version
43module.exports.default = stringWidth;