Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript word count cut off

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.

like image 654
webmaster alex l Avatar asked Dec 06 '22 23:12

webmaster alex l


2 Answers

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>
like image 182
Chris Baker Avatar answered Dec 17 '22 16:12

Chris Baker


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
like image 33
gilly3 Avatar answered Dec 17 '22 18:12

gilly3