TheWebs
TheWebs

Reputation: 12913

What is the best way to get the first x number of words from a string javascript

With out using jquery, what is the easiest way to do this? If I have a string containing 600 words, and I want only the first 100 or so words and then trail off with: ... what is the easiest way to do this?

I found: replace(/(([^\s]+\s\s*){40})(.*)/,"$1…"); But I don' understand regex enough to know if this is right or not.

Upvotes: 2

Views: 1789

Answers (2)

asontu
asontu

Reputation: 4659

@dfsq's solution is a nice straight forward one, but in the interest of learning :)

To try and understand regexes, I would advice looking at the flow-chart-alike visualisation that Debuggex gives you, and experiment with substitution on Regex101. (links contain the regex unaltered from your question)

I would make some small modifications:

  1. The . doesn't match new-lines, one way to do that is to match [\s\S] in stead, which matches absolutely every character
  2. This: [^\s]+\s\s* can be untangled and optimized to \S+\s+, but I would turn it around and make it \s*\S+ so that the ... comes after the last word without a space in between.

Which would result in this:

((\s*\S+){40})([\s\S]*)

Regular expression visualization

Regex101 substitution in action

Upvotes: 4

Fourat
Fourat

Reputation: 2447

That's quite simple I guess (I don't know if this is the best way) !

for(var i=1;i <= numberOfWords;i++) {
    var word = mystr.substr(0,mystr.indexOf(' ')+1).trim();
    arrayOfWords.push(word);
    mystr = mystr.substr(mystr.indexOf(' '),mystr.length-1).trim();
}

Try for yourself: http://jsfiddle.net/fourat05/w386mxaa/

Upvotes: 1

Related Questions