Search This Blog

Friday, 10 March 2017

Javacsript::Reducing text by word limit

Reducing text by word limit

function excerpt(str, nwords) {
  var words = str.split(' ');
  words.splice(nwords, words.length-1);
  return words.join(' ') +
    (words.length !== str.split(' ').length ? '…' : '');
}

It allows you to truncate a string to a particular number of words and it adds ellipsis if necessary. It works with text that may have other inline tags such as strong or em or links.

No comments:

Post a Comment