I have a div with an ID “shortblogpost”. I would like to count up to 27th word then stop and add “…” at the end.
I was trying the following code. Problem, Its counting letters and not words. I think its using jQuery and not strait up JavaScript?
I need to use JavaScript for various server reasons only
<script type="text/javascript">
var limit = 100,
text = $('div.shortblogpost').text().split(/\s+/),
word,
letter_count = 0,
trunc = '',
i = 0;
while (i < text.length && letter_count < limit) {
word = text[i++];
trunc += word+' ';
letter_count = trunc.length-1;
}
trunc = $.trim(trunc)+'...';
console.log(trunc);
</script>
Ty all in advance for any help.
Truncate function.
Use: truncate(‘This is a test of this function’, 2);
Returns: This is…
Use: truncate(‘This is a test of this function’, 5, ‘+++’);
Returns: This is a test of+++
Edit:
Quick and dirty implement by parameters of OP: