index.js 879 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const stripAnsi = require('strip-ansi');
  3. const isFullwidthCodePoint = require('is-fullwidth-code-point');
  4. const emojiRegex = require('emoji-regex');
  5. const stringWidth = string => {
  6. string = string.replace(emojiRegex(), ' ');
  7. if (typeof string !== 'string' || string.length === 0) {
  8. return 0;
  9. }
  10. string = stripAnsi(string);
  11. let width = 0;
  12. for (let i = 0; i < string.length; i++) {
  13. const code = string.codePointAt(i);
  14. // Ignore control characters
  15. if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
  16. continue;
  17. }
  18. // Ignore combining characters
  19. if (code >= 0x300 && code <= 0x36F) {
  20. continue;
  21. }
  22. // Surrogates
  23. if (code > 0xFFFF) {
  24. i++;
  25. }
  26. width += isFullwidthCodePoint(code) ? 2 : 1;
  27. }
  28. return width;
  29. };
  30. module.exports = stringWidth;
  31. // TODO: remove this in the next major version
  32. module.exports.default = stringWidth;