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 ...
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 ...
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...'));
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));
use
strArr[] = str.split(" ");
str[0]
, str[1]
, str[2]
, str[3]
is the resultant what you want to use.