truncate.js 816 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. function truncate(str, options = {}) {
  3. if (typeof str !== 'string') throw new TypeError('str must be a string!');
  4. const length = options.length || 30;
  5. const omission = options.omission || '...';
  6. const { separator } = options;
  7. const omissionLength = omission.length;
  8. if (str.length < length) return str;
  9. if (separator) {
  10. const words = str.split(separator);
  11. let result = '';
  12. let resultLength = 0;
  13. for (const word of words) {
  14. if (resultLength + word.length + omissionLength < length) {
  15. result += word + separator;
  16. resultLength = result.length;
  17. } else {
  18. return result.substring(0, resultLength - 1) + omission;
  19. }
  20. }
  21. } else {
  22. return str.substring(0, length - omissionLength) + omission;
  23. }
  24. }
  25. module.exports = truncate;