Javascript substr();按字数限制而不是字符 [英] Javascript substr(); limit by word not char

查看:105
本文介绍了Javascript substr();按字数限制而不是字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用字而不是字符来限制子字符串。我正在考虑正则表达式和空格但不知道如何将它拉下来。

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.

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

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!

推荐答案

function trim_words(theString, numWords) {
    expString = theString.split(/\s+/,numWords);
    theNewString=expString.join(" ");
    return theNewString;
}

这篇关于Javascript substr();按字数限制而不是字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆