Posted By

segdeha on 06/19/09


Tagged

javascript String truncate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Vordreller


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


 / Published in: JavaScript
 

  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
Posted By: zettersten on April 9, 2011

where is STR defined?

Posted By: khw on September 27, 2012

Don't use the function above, it doesn't work.

Don't use any function. Just use:

str.substring(0, 90).replace(/\w+$/, '');

Posted By: ehask71 on November 15, 2012

Working version

function truncate(str, limit) { var bits, i; if ("string" !== typeof str) { return ''; } bits = str.split(''); if (bits.length > limit) { for (i = bits.length - 1; i > -1; --i) { if (i > limit) { bits.length = i; } else if (' ' === bits[i]) { bits.length = i; break; } } bits.push('...'); } return bits.join(''); }

You need to login to post a comment.