0

Lets say I have a string: "This is a string of words that I want to pair"

I ideally want this as the result:

["This is", "is a", "a string"....]

I have this regex:

let str = "This is a string of words that I want to pair"
let regexp = /\b[0-9A-Za-z]+\s+\b[0-9A-Za-z]+/g

let array = [...str.matchAll(regexp)]

But it is returning:

["This is", "a string", "of words"...]

How do I correct this?

Morgan Allen
  • 3,291
  • 8
  • 62
  • 86

3 Answers3

2

Why use a regex for that, a simple loop with a split would work perfectly. :

let str = "This is a string of words that I want to pair"

let words = str.split(' ');
let finalArray = []
for(var i = 0 ; i < words.length; i++ ) {
  // validate that the next words exists
  if(words[i + 1]) {
    let pairedWords = words[i] + " " + words[i + 1];
    finalArray.push(pairedWords);
  }
}

console.log(finalArray);
Nicolas
  • 8,077
  • 4
  • 21
  • 51
1

You may use this regex with a lookahead:

/\b(\w+)(?=(\s+\w+))/g

This regex matches a single word with a lookahead condition that says that matches word must be followed by 1+ whitespaces followed by another word. We capture matched word and lookahead word in 2 separate groups that we have to concatenate in final result.

const s = 'This is a string of words that I want to pair';

const regex = /\b(\w+)(?=(\s+\w+))/g;

var result = [];
var m;

while ((m = regex.exec(s)) != null) {
  result.push(m[1] + m[2]);
}

console.log(result);
anubhava
  • 761,203
  • 64
  • 569
  • 643
-1

I think something like that should works:

    const s = "This is a string of words that I want to pair";
    console.log([...(s.matchAll(/[^ ]+(?: [^ ]+)?/g))]);

This should produce an array of 6 element, 5 pairs plus "pair" alone at the end.

georg
  • 211,518
  • 52
  • 313
  • 390
ZER0
  • 24,846
  • 5
  • 51
  • 54