/ Published in: JavaScript

Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Author: Andrew Hedges, [email protected] * License: free to use, alter, and redistribute without attribution */ /** * Truncate a string to the given length, breaking at word boundaries and adding an elipsis * @param string str String to be truncated * @param integer limit Max length of the string * @return string */ var truncate = function (str, limit) { var bits, i; if (STR !== 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(''); }; // END: truncate
Comments
