【发布时间】:2016-04-11 17:11:55
【问题描述】:
我有一个很长的短语,我想显示前 4 个单词。
示例:
The style of this paper is a combination of an external stylesheet, and internal style.
变成这样:
这个风格……
【问题讨论】:
标签: javascript css angularjs html
我有一个很长的短语,我想显示前 4 个单词。
示例:
The style of this paper is a combination of an external stylesheet, and internal style.
变成这样:
这个风格……
【问题讨论】:
标签: javascript css angularjs html
您可以为此使用正则表达式。它需要前四个单词并添加一些点,
var text = 'The style of this paper is a combination of an external stylesheet, and internal style.';
document.write(text.replace(/^((\w*\W*){0,4}).*/, '$1...'));
【讨论】:
您可以创建一个函数,从元素的文本中返回前 N 个单词。例如:
function firstWords(wrapperId, wordCount) {
var element = document.getElementById(wrapperId);
var textArray = element.textContent.split(/\s/);
if(textArray.length >= wordCount) {
return textArray.slice(0, wordCount).join(" ");
} else {
return textArray.join(" ");
}
}
如果包装器的 ID 为“foo”,例如
<div id="foo">This is a sample text!</div>
你可以打电话
console.log(firstWords("foo", 4));
【讨论】:
使用
strArr[] = str.split(" ");
str[0], str[1], str[2], str[3] 是你想要使用的结果。
【讨论】: