Skip to content

Instantly share code, notes, and snippets.

View mattucf's full-sized avatar

Matt Brown mattucf

View GitHub Profile
@mattucf
mattucf / gist:950011
Created April 30, 2011 21:33
word-preserving truncate
splitBody: function(body, max_chars){
var truncate_pos = max_chars - 1;
var word_char = XRegExp("\\p{L}");
if (body.length > max_chars){
if (word_char.test(body.charAt(truncate_pos))){
var next = (body.length > max_chars + 1) ? body.charAt(max_chars) : '';
if (next && word_char.test(next)){
// Roll back the truncate position to the nearest word boundary.
for (var i = truncate_pos; i > 0 && word_char.test(body.charAt(i)); i--);
(i > 0) && (truncate_pos = i);