index.js 923 B

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