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

very quick and dirty

$("#textArea").val().split(/\s/).length
于 2009-11-02T16:40:18.260 回答
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
}

您还应该决定是否将数字视为单词,以及是否将单个字母视为单词。

于 2011-03-28T06:48:23.833 回答