如何将句子截断为一定数量的单词(NB.而不是字母)?
我想用split(" ")
,但那我怎么算数字呢?
例如:
Javascript word count cut off
=> Javascript word count
Want better search results? See our search tips!
=> Want better search
Ami*_*far 32
您可以使用split
[MDN]和join
[MDN].
"Want better search results? See our search tips".split(" ").splice(0,3).join(" ")
Run Code Online (Sandbox Code Playgroud)
小智 5
这是我为Meteor应用程序编写的“更多信息”功能。它接受maxWords参数并使用jquery的text()方法剥离html标签。
希望能帮助到你!
function readMore(string, maxWords) {
var strippedString = $("<p>" + string + "</p>").text().trim();
var array = strippedString.split(" ");
var wordCount = array.length;
var string = array.splice(0, maxWords).join(" ");
if(wordCount > maxWords) {
string += "...";
}
return string ;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9569 次 |
最近记录: |