tags:

views:

581

answers:

2

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!

+2  A: 

if you're satisfied with a not-quite accurate solution, you could simply keep a running count on the number of space characters within the text and assume that it is equal to the number of words.

Otherwise, I would use split() on the string with " " as the delimiter and then count the size of the array that split returns.

Brian Schroth
Thanks guys :) I now have a great way to get the count but with my limited abilities how do I take this and spit out a chunck of text limited to say 200 words?I am able to get the overall count of spaces but not sure what to do with it :) tnx. var $postLength = $postBody.split(/\s/).length
JadedBat
Are you saying that given a chunk of text that is perhaps 300 words long you would like to get the chunk containing the first 200 words? split(" ") will return the array of words, you would just have to loop through it and concatenate the first 200 elements of the array together. Or if you used my less accurate but much faster initial suggesting, you could just loop through the string counting the number of space characters and when you reach #200 take the substring from the start to the location of the 200th space.
Brian Schroth
Thanks for helping :) here is the method I came up with:var $i = 0;var $maxWords = 50;var $postBody = $("#myDiv").text().split(' ');while($i < $maxWords){ $("#results").append($postBody[$i] + " "); $i++; }
JadedBat
looks like it will work. Make sure you give it a few good test cases to make sure it works as expected with multiple spaces in a row...and I'd look out for the possibility of going out of bounds on the array. If the postBody is less than $maxWords in length, it seems that "append($postBody[$i] + " ") would go out of bounds on the array once it reached the length of the post body.
Brian Schroth
+1  A: 

very quick and dirty

$("#textArea").val().split(/\s/).length
Marek Karbarz