-1

I need extract some information from test string using "(\w)\w" pattern with RegExp in JavaScript. I want to get all results with capturing groups. For example: "(t)e","(e)s","(s)t" and so on. How can I achieve this.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476

1 Answers1

0

If you want to have the values in all capturing groups, you can get those matching using 2 capturing groups inside a positive lookahead.

The value of te is in capture group 1, the value of t in group 2. The first value in the array is empty, as the pattern itself only matches a position.

(?=((\w)\w))

Regex demo

const regex = /(?=((\w)\w))/g;
let s = "test string";
console.log([...s.matchAll(regex)]);

If you use a single capturing group (?=(\w\w)) you will have the values te, es, st etc... in group 1.

regex demo

The fourth bird
  • 127,136
  • 16
  • 45
  • 63