Itamar S
Itamar S

Reputation: 1565

Use .split() on every x words

I've had this question for a while now, and have been wondering if it'd be possible to use the .split() method to split a string every x words. For example, if I were to have a string saying I am coming for you world!, I would want to split so every 2 words create an element, resulting in an array: ['I am', 'coming for', 'you world!'].

Upvotes: 1

Views: 95

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

You can .match non-spaces, followed by a space, followed by non-spaces:

console.log(
  'I am coming for you world!'
    .match(/\S+ +\S+/g)
);

If you had to use .split, and .split alone, with no further processing, it's barely possible, by looking behind for exactly 1, or 3, or 5 (etc) spaces between the matched space and the beginning of the string (but I wouldn't recommend this approach):

console.log(
  'I am coming for you world!'
    .split(/(?<=^\S+ \S+(?: \S+ +\S+)*) /)
);

Upvotes: 4

Related Questions