javascript 将句子截断为一定数量的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7374758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Truncate sentence to a certain number of words
提问by fish man
How can a sentence be truncated to a certain number of words (NB. not letters)?
如何将一个句子截断为一定数量的单词(注意,不是字母)?
I thought to use split(" ")
, but then how do I count out words?
我想使用split(" ")
,但是我如何计算单词?
For example:
例如:
Javascript word count cut off
=>Javascript word count
Want better search results? See our search tips!
=>Want better search
Javascript word count cut off
=>Javascript word count
Want better search results? See our search tips!
=>Want better search
回答by Amir Raminfar
You can use split
[MDN]and join
[MDN].
您可以使用split
[MDN]和join
[MDN]。
"Want better search results? See our search tips".split(" ").splice(0,3).join(" ")
回答by Guilherme Solinscki
Here's a "read more" function I wrote for my Meteor app. It accepts a maxWords parameter and strips html tags using jquery's text() method.
这是我为 Meteor 应用程序编写的“阅读更多”功能。它接受一个 maxWords 参数并使用 jquery 的 text() 方法去除 html 标签。
Hope it helps!
希望能帮助到你!
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 ;
}
回答by Rafi
Pure solution with ES6, defaults to 10 words
ES6纯解,默认10字
const truncate = (str, max = 10) => {
const array = str.trim().split(' ');
const ellipsis = array.length > max ? '...' : '';
return array.slice(0, max).join(' ') + ellipsis;
};
回答by Timbits
Splitting works, as you have described it. If you use a RegExp, however, you don't have to split the whole string:
正如您所描述的,拆分工作。但是,如果您使用 RegExp,则不必拆分整个字符串:
var str = "Lions and tigers and bears";
var exp = /[A-Z|a-z]+/g;
var a = exp.exec(str); // Lions
var b = exp.exec(str); // and
var c = exp.exec(str); // tigers