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,065
  • 5
  • 50
  • 81

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
  • 7,819
  • 3
  • 20
  • 47
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
  • 713,503
  • 59
  • 514
  • 593
-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
  • 204,715
  • 48
  • 286
  • 369
ZER0
  • 23,634
  • 5
  • 48
  • 53