Last active
December 11, 2015 06:49
-
-
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 `...`
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
/* 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