0

I have a long phrase and I want to show the first 4 words.

example:

The style of this paper is a combination of an external stylesheet, and internal style.

become like this:

The style of this ...

Hadi J
  • 16,989
  • 4
  • 36
  • 62
  • 1
    may be help you http://stackoverflow.com/questions/36442069/how-to-reduce-the-length-of-the-paragraph-by-dots – Hadi J Apr 11 '16 at 08:38
  • Look this: http://stackoverflow.com/questions/5956610/how-to-select-first-10-words-of-a-sentence – Lifka Apr 11 '16 at 08:39

3 Answers3

2

You could use a regular expression for that. It takes the first four words and adds some dots,

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...'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can create a function which returns the first N words from the text of an element. For example:

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

Afterwards if the wrapper has ID "foo" for example as

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

you can call

console.log(firstWords("foo", 4));
Dropout
  • 13,653
  • 10
  • 56
  • 109
-2

use

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

str[0] , str[1], str[2], str[3] is the resultant what you want to use.

ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
amitguptageek
  • 537
  • 3
  • 13