Created
April 30, 2011 21:33
-
-
Save mattucf/950011 to your computer and use it in GitHub Desktop.
word-preserving truncate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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