-2

I have a string like this:

[Value1][Value2][Value3][Value4][Value5]

And I need to get the value for each pair of square brackets. There can be 1 pair to a maximum of 5 pairs.

I've tried this:

var regExp = /\[(.*?)\]/
var matches = regExp.exec([A][B]");

console.log(matches[1]);
console.log(matches[2]);

I expect the console to output A and B, however for B I get undefined.

1x2x3x4x
  • 592
  • 8
  • 26

1 Answers1

0

You could use String.prototype.match with regex global flag

var regExp = /\[(.*?)\]/g;
var matches = "[A][B]".match(regExp);

console.log(matches[0]);
console.log(matches[1]);

Edit: for only getting contents in quare brackets:

var regExp = /(?<=\[).*?(?=\])/g;
var matches = "[A][B]".match(regExp);

console.log(matches[0]);
console.log(matches[1]);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • @xxxxxxxxxxxxx ... From how the OP was asking the Q. and presenting the problem I would assume that the expected result was rather `A` and `B` instead of `[A]` and `[B]`. – Peter Seliger Jul 21 '20 at 14:19
  • 1
    In order to retrieve the captured values in between the brackets one needs to change line 2 of your A. to `... matches = [..."[A][B]".matchAll(regExp)].map(([match, value]) => value);` – Peter Seliger Jul 21 '20 at 14:36
  • I've seen that while testing it but I just removed one char at the start and end of the resulting string. However your solution is more elegant. Thanks to both. – 1x2x3x4x Jul 22 '20 at 09:05