/ Published in: JavaScript
Expand |
Embed | Plain Text
/** * 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
Subscribe to comments
You need to login to post a comment.

where is STR defined?
Don't use the function above, it doesn't work.
Don't use any function. Just use:
str.substring(0, 90).replace(/\w+$/, '');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(''); }