我有一個很長的短語,我想顯示前4個單詞。顯示html中短語的前4個單詞
例如:
The style of this paper is a combination of an external stylesheet, and internal style.
變成了這個樣子:
這樣做的風格...
我有一個很長的短語,我想顯示前4個單詞。顯示html中短語的前4個單詞
例如:
The style of this paper is a combination of an external stylesheet, and internal style.
變成了這個樣子:
這樣做的風格...
你可以使用正則表達式爲。它採用前四個字和增加了一些點,
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...'));
使用
strArr[] = str.split(" ");
str[0]
,str[1]
,str[2]
,str[3]
是你想要使用的結果。
這並沒有真正回答這個問題。 .. –
您可以創建一個函數,它返回元素文本中的前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));
可能幫助你http://stackoverflow.com/questions/36442069/how-to-reduce-the-length-of -this-paragraph-by-dots –
看起來這個:http://stackoverflow.com/questions/5956610/how-to-select-first-10-words-of-a-sentence – Lifka