Divide a string into an array of n words by index

I have a string that I would like to split in an array that has (for example) 3 words per index. What I would also like to do is to meet a new line character in this line so that it “skips” the 3 word limit and puts it in a new index and starts adding words to this new index until it reaches 3 again, Example

var text = "this is some text that I'm typing here \n yes I really am"

var array = text.split(magic)

array == ["this is some", "text that I'm", "typing here", "yes I really", "am"]

I tried looking for regular expressions, but so far I can’t understand the meaning of the syntax used in regex.

I wrote a way to a complex function that splits my string into lines of 3, first breaking it into an array of individual words, using .split(" ");, and then using a loop to add it 3 in each array. But with this I can not accept the new line symbol.

+4
source share
5 answers

You can try with this template:

var result = text.match(/\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g);

since quantifier {0,2}default greedy, it will take a value less than 2 (N-1) , only if found new row (since new rows are not allowed here: [^\w\n]+) or if you are the end of the line.

+4
source

If you are interested in the regexp solution, it will look like this:

   text.match(/(\S+ \S+ \S+)|(\S+ \S+)(?= *\n|$)|\S+/g)
   // result ["this is some", "text that I'm", "typing here", "yes I really", "am"]

Explanation: Match either three whitespace words, or two words followed by spaces + a new line or just one word (a “word” is just a sequence of non-spaces).

:

text.match(/((\S+ ){N-1}\S+)|(\S+( \S+)*)(?= *\n|$)|\S+/g)

( N-1 ).

+2

- :

words = "this is some text that I'm typing here \n yes I really am".split(" ");
result = [];
temp = "";

for (i = 0; i < words.length; i++) {
  if ((i + 1) % 3 == 0) {
    result.push(temp + words[i] + " ");
    temp = "";
  } else if (i == words.length - 1) {
    result.push(temp + words[i]);
  } else {
    temp += words[i] + " ";
  }
}

console.log(result);

, , , . , , , , temp , temp.

+1

, , 3:

"this is some text that I'm typing here \n yes I really am".match(/\S+\s+\S+\s+\S+/g)
=> ["this is some", "text that I'm", "typing here \n yes", "I really am"]

:

"this is some text that I'm typing here \n yes I really am FOO".match(/\S+\s+\S+\s+\S+/g)

, "FOO".

0

: ((?:(?:\S+\s){3})|(?:.+)(?=\n|$))

0

Source: https://habr.com/ru/post/1540128/


All Articles