Truncate sentence to a certain number of words
Here's a "read more" function I wrote for my Meteor app. It accepts a maxWords parameter and strips html tags using jquery's text() method.
Hope it helps!
function readMore(string, maxWords) {
var strippedString = $("<p>" + string + "</p>").text().trim();
var array = strippedString.split(" ");
var wordCount = array.length;
var string = array.splice(0, maxWords).join(" ");
if(wordCount > maxWords) {
string += "...";
}
return string ;
}
You can use split
[MDN] and join
[MDN].
"Want better search results? See our search tips".split(" ").splice(0,3).join(" ")