Skip to content

Instantly share code, notes, and snippets.

@mattucf
Created April 30, 2011 21:33
Show Gist options
  • Save mattucf/950011 to your computer and use it in GitHub Desktop.
Save mattucf/950011 to your computer and use it in GitHub Desktop.
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);
}
}
return [body.substr(0, truncate_pos + 1), body.substr(truncate_pos + 1)];
}
return [body, ''];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment