blob: f4d261a96a099ee6b9dcfbf7b050d6e2f42075a2 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001'use strict';
2const stripAnsi = require('strip-ansi');
3const isFullwidthCodePoint = require('is-fullwidth-code-point');
Tim van der Lipped3425b92022-01-07 14:05:09 +01004const emojiRegex = require('emoji-regex');
Yang Guo4fd355c2019-09-19 10:59:03 +02005
Tim van der Lipped3425b92022-01-07 14:05:09 +01006const stringWidth = string => {
7 if (typeof string !== 'string' || string.length === 0) {
Yang Guo4fd355c2019-09-19 10:59:03 +02008 return 0;
9 }
10
Tim van der Lipped3425b92022-01-07 14:05:09 +010011 string = stripAnsi(string);
12
13 if (string.length === 0) {
14 return 0;
15 }
16
17 string = string.replace(emojiRegex(), ' ');
Yang Guo4fd355c2019-09-19 10:59:03 +020018
19 let width = 0;
20
Tim van der Lipped3425b92022-01-07 14:05:09 +010021 for (let i = 0; i < string.length; i++) {
22 const code = string.codePointAt(i);
Yang Guo4fd355c2019-09-19 10:59:03 +020023
24 // Ignore control characters
25 if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
26 continue;
27 }
28
29 // Ignore combining characters
30 if (code >= 0x300 && code <= 0x36F) {
31 continue;
32 }
33
34 // Surrogates
35 if (code > 0xFFFF) {
36 i++;
37 }
38
39 width += isFullwidthCodePoint(code) ? 2 : 1;
40 }
41
42 return width;
43};
Tim van der Lipped3425b92022-01-07 14:05:09 +010044
45module.exports = stringWidth;
46// TODO: remove this in the next major version
47module.exports.default = stringWidth;