2016-04-11 4 views
0

長いフレーズがあり、最初の4語を表示します。は、フレーズの最初の4語をhtmlで表示します。

例:

The style of this paper is a combination of an external stylesheet, and internal style. 
このようになる

本のスタイル...

+1

が助けあなたをすることができ、http://stackoverflow.com/questions/36442069/how-to-reduce-the-length-of最初の4つの単語を取り、いくつかの点を追加します-the-by-dots-by-dots –

+0

これを見てください:http://stackoverflow.com/questions/5956610/how-to-select-first-10-words-of-a-sentence – Lifka

答えて

2

を呼び出すことができます。それは

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...'));

-2

使用

strArr[] = str.split(" "); 

str[0]str[1]str[2]str[3]はあなたが使用したいものです。

+0

これは本当に質問に答えるものではありません。 .. –

0

要素のテキストから最初のN語を返す関数を作成できます。たとえば:ラッパーは

<div id="foo">This is a sample text!</div> 

として例えばID "foo" を持っている場合はその後

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(" "); 
    } 
} 

あなたはあなたがそのための正規表現を使用することができます

console.log(firstWords("foo", 4));