Javascript substr (); the word restriction is not char

I would like to limit substr to words, not characters. I think about regex and spaces, but don't know how to do this.

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

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

It's great, but it splits the words in half :) Thanks in advance!

+3
source share
4 answers
function trim_words(theString, numWords) {
    expString = theString.split(/\s+/,numWords);
    theNewString=expString.join(" ");
    return theNewString;
}
+10
source

if you are not satisfied with the exact solution, you can simply save the number of starts by the number of spaces in the text and assume that it is equal to the number of words.

split() "" , , .

+4

very fast and dirty

$("#textArea").val().split(/\s/).length
+1
source

I suggest that you also need to consider punctuation marks and other characters other than words, not spaces. You want 200 words, not counting whitespace and non-letter characters.

var word_count = 0;
var in_word = false;

for (var x=0; x < text.length; x++) {
   if ( ... text[x] is a letter) {
      if (!in_word) word_count++;
      in_word = true;
   } else {
      in_word = false;
   }

   if (!in_word && word_count >= 200) ... cut the string at "x" position
}

You must also decide whether you treat the words as a word and whether you consider single letters as a word.

+1
source

Source: https://habr.com/ru/post/1721714/


All Articles