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+++
function truncate (text, limit, append) {
if (typeof text !== 'string')
return '';
if (typeof append == 'undefined')
append = '...';
var parts = text.split(' ');
if (parts.length > limit) {
// loop backward through the string
for (var i = parts.length - 1; i > -1; --i) {
// if i is over limit, drop this word from the array
if (i+1 > limit) {
parts.length = i;
}
}
// add the truncate append text
parts.push(append);
}
// join the array back into a string
return parts.join(' ');
}
Edit: Quick and dirty implement by parameters of OP:
<script type="text/javascript">
// put truncate function here...
var ele = document.getElementById('shortblogpost');
ele.innerHTML = truncate(ele.innerHTML, 20);
</script>
This can be done in one line of code:
myString.replace(/(([^\s]+\s+){27}).+/, "$1...");
Or, you can make it a function:
function truncateString(s, wordCount)
{
var expr = new RegExp("(([^\\s]+\\s+){" + wordCount + "}).+");
return s.replace(expr, "$1...");
}
So, to make this work for your code, you can do:
var post = $('div.shortblogpost').text(); // get the text
post = postText.replace(/(([^\s]+\s+){27}).+/, "$1..."); // truncate the text
$('div.shortblogpost').text(post); // update the post with the truncated text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With