truncate.js 658 B

123456789101112131415161718192021
  1. var toString = require('../lang/toString');
  2. var trim = require('./trim');
  3. /**
  4. * Limit number of chars.
  5. */
  6. function truncate(str, maxChars, append, onlyFullWords){
  7. str = toString(str);
  8. append = append || '...';
  9. maxChars = onlyFullWords? maxChars + 1 : maxChars;
  10. str = trim(str);
  11. if(str.length <= maxChars){
  12. return str;
  13. }
  14. str = str.substr(0, maxChars - append.length);
  15. //crop at last space or remove trailing whitespace
  16. str = onlyFullWords? str.substr(0, str.lastIndexOf(' ')) : trim(str);
  17. return str + append;
  18. }
  19. module.exports = truncate;