2

I have a text like: "Something, some text between commas, between comma, and more text between commas, something something." I need to match every piece of text that is insides two commas. I found this regex /,([^,]*),/g, but it is returning me:

, some text between commas,

, and more text between commas,

but i need it to return:

some text between commas

between comma

and more text between commas

Need your help guys.

Community
  • 1
  • 1
Abhner Araujo
  • 41
  • 1
  • 7

2 Answers2

2

One way is to split the on the comma's (including optional whitespaces).
Then remove the first & last elements of the array.
But that works fine as long those starting & ending comma's aren't required in the resulting array.

Example snippet:

var str = "Something, some text between commas, between comma, and more text between commas, something something";

var arr = str.split(/\s*,\s*/).slice(1,-1);

console.log(arr);

But if you do need to keep the start&end comma's in the result?
Then matching with a lookahead should do the trick.

Example snippet:

var str = "Something, some text between commas, between comma, and more text between commas, something something";

var re = /,[^,]*(?=,)/g;
var arr = [];
var match;
while (match = re.exec(str)) {
   arr.push(match[0]+',');
}

console.log(arr);

(although I don't really see the point to keep those comma's)

LukStorms
  • 28,916
  • 5
  • 31
  • 45
0

Use this regex with a positive lookahead to ensure that the text is between commas without consuming the second comma.

/,([^,]*)(?=,)/g

See here for a working example: https://regexr.com/3qkui

Boric
  • 822
  • 7
  • 26
  • I am not sure it is relevant, but your results are not in line with OP. OP wants `, some text between commas,` as first match, while you have `, some text between commas` (without the trailing comma). – Wiktor Stribiżew Jun 06 '18 at 19:23