Javascript substr(); limit by word not char

user201063 picture user201063 · Nov 2, 2009 · Viewed 8.9k times · Source

I would like to limit the substr by words and not chars. I am thinking regular expression and spaces but don't know how to pull it off.

Scenario: Limit a paragraph of words to 200 words using javascript/jQuery.

var $postBody = $postBody.substr(' ',200); 

This is great but splits words in half :) Thanks ahead of time!

Answer

ProNeticas picture ProNeticas · Mar 28, 2011
function trim_words(theString, numWords) {
    expString = theString.split(/\s+/,numWords);
    theNewString=expString.join(" ");
    return theNewString;
}