Javascript word count cut off
-
12-11-2019 - |
Question
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.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow