You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wide-truncate.js 858B

12345678910111213141516171819202122232425262728293031
  1. 'use strict'
  2. var stringWidth = require('string-width')
  3. var stripAnsi = require('strip-ansi')
  4. module.exports = wideTruncate
  5. function wideTruncate (str, target) {
  6. if (stringWidth(str) === 0) {
  7. return str
  8. }
  9. if (target <= 0) {
  10. return ''
  11. }
  12. if (stringWidth(str) <= target) {
  13. return str
  14. }
  15. // We compute the number of bytes of ansi sequences here and add
  16. // that to our initial truncation to ensure that we don't slice one
  17. // that we want to keep in half.
  18. var noAnsi = stripAnsi(str)
  19. var ansiSize = str.length + noAnsi.length
  20. var truncated = str.slice(0, target + ansiSize)
  21. // we have to shrink the result to account for our ansi sequence buffer
  22. // (if an ansi sequence was truncated) and double width characters.
  23. while (stringWidth(truncated) > target) {
  24. truncated = truncated.slice(0, -1)
  25. }
  26. return truncated
  27. }