Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Last active December 11, 2015 06:49
Show Gist options
  • Save ajcrites/4562156 to your computer and use it in GitHub Desktop.
Save ajcrites/4562156 to your computer and use it in GitHub Desktop.
Truncate element text length to 100 characters, but do not split words (you can go over 100 characters to do so). If it is truncated, i.e. shorter than the original length, add `...`
/* Setup */
for (var x = 0; x < 5; x++) {
$("<div>").appendTo("body");
}
$("div").each(function () {
$(this).text((new Array(Math.floor(20 + Math.random() * 4))).join('text '));
});
/* Truncation */
$("div").text(function (_, text) {
if (!$(this).data('full-text')) {
$(this).data('full-text', text);
}
var lastSpace = text.substr(100).split(/\s/).join(' ').indexOf(' ');
if (lastSpace > -1) {
return text.substr(0, 100 + lastSpace) + '...'
}
});
/* Result */
$("div").text(function (_, text) {
return text + ' ' + text.length;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment