JavaScript substr();按字限制而不是字符

发布于 2024-08-09 15:20:15 字数 197 浏览 7 评论 0原文

我想用单词而不是字符来限制子字符串。我正在考虑正则表达式和空格,但不知道如何实现。

场景:使用 javascript/jQuery 将一段单词限制为 200 个单词。

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

这很棒,但将单词分成两半:) 提前谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

过潦 2024-08-16 15:20:15
function trim_words(theString, numWords) {
    expString = theString.split(/\s+/,numWords);
    theNewString=expString.join(" ");
    return theNewString;
}
function trim_words(theString, numWords) {
    expString = theString.split(/\s+/,numWords);
    theNewString=expString.join(" ");
    return theNewString;
}
小…红帽 2024-08-16 15:20:15

如果您对不太准确的解决方案感到满意,您可以简单地对文本中的空格字符数进行连续计数,并假设它等于单词数。

否则,我会在以“”作为分隔符的字符串上使用 split() ,然后计算 split 返回的数组的大小。

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.

心房的律动 2024-08-16 15:20:15

又快又脏

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

very quick and dirty

$("#textArea").val().split(/\s/).length
2024-08-16 15:20:15

我想您还需要考虑标点符号和其他非单词、非空白字符。您需要 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
}

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

I suppose you need to consider punctuation and other non-word, non-whitespace characters as well. 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 should also decide whether you treat digits as a word, and whether you treat single letters as a word.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文