JavaScript substr();按字限制而不是字符
我想用单词而不是字符来限制子字符串。我正在考虑正则表达式和空格,但不知道如何实现。
场景:使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您对不太准确的解决方案感到满意,您可以简单地对文本中的空格字符数进行连续计数,并假设它等于单词数。
否则,我会在以“”作为分隔符的字符串上使用 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.
又快又脏
very quick and dirty
我想您还需要考虑标点符号和其他非单词、非空白字符。您需要 200 个单词,不包括空格和非字母字符。
您还应该决定是否将数字视为一个单词,以及是否将单个字母视为一个单词。
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.
You should also decide whether you treat digits as a word, and whether you treat single letters as a word.