Truncate a string to a set length, breaking at word boundaries


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Author: Andrew Hedges, [email protected]
  3.  * License: free to use, alter, and redistribute without attribution
  4.  */
  5.  
  6. /**
  7.  * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
  8.  * @param string str String to be truncated
  9.  * @param integer limit Max length of the string
  10.  * @return string
  11.  */
  12. var truncate = function (str, limit) {
  13. var bits, i;
  14. if (STR !== typeof str) {
  15. return '';
  16. }
  17. bits = str.split('');
  18. if (bits.length > limit) {
  19. for (i = bits.length - 1; i > -1; --i) {
  20. if (i > limit) {
  21. bits.length = i;
  22. }
  23. else if (' ' === bits[i]) {
  24. bits.length = i;
  25. break;
  26. }
  27. }
  28. bits.push('...');
  29. }
  30. return bits.join('');
  31. };
  32. // END: truncate

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.