1

I have written a (?!,)(.*?)(?=,) regex in JavaScript .

This regex returns 20 matching groups, but I want to get first 5 groups.

How can I do this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Wardruna
  • 198
  • 4
  • 23

1 Answers1

0

Just use match/split and then slice the array to get the necessary items:

var re = /[^,]+/g; 
var str = 'word1, word2, word3, word4, word5, word6, word7, word8, word9, word10, word11, word12, ';

alert(str.match(re).slice(0, 5));

var splts = str.split(',').slice(0,5);
alert(splts);

Since you are just looking for strings between commas, I suggest using [^,]+ regex.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563