4

文字ではなく単語で substr を制限したいと思います。正規表現とスペースを考えていますが、それをやってのける方法がわかりません。

シナリオ: javascript/jQuery を使用して、単語の段落を 200 単語に制限します。

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

これは素晴らしいですが、単語を半分に分割します:) 事前に感謝します!

4

4 に答える 4

11
function trim_words(theString, numWords) {
    expString = theString.split(/\s+/,numWords);
    theNewString=expString.join(" ");
    return theNewString;
}
于 2011-03-28T06:37:46.597 に答える
4

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.

于 2009-11-02T16:36:20.740 に答える
1

句読点やその他の単語や空白以外の文字も考慮する必要があると思います。空白や文字以外の文字を数えずに、200語が必要です。

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
}

また、数字を単語として扱うかどうか、および1文字を単語として扱うかどうかも決定する必要があります。

于 2011-03-28T06:48:23.833 に答える
1

非常に速くて汚い

$("#textArea").val().split(/\s/).length
于 2009-11-02T16:40:18.260 に答える