bflemi3 bflemi3 - 5 months ago 12
Javascript Question

Capture group certain number of times with regular expression but last group has remaining values

Given a string delimited by a colon and similar to this...

xvf:metric:admin:click


I need to capture three groups...

xvf
metric
admin:click


Or another example:

one:two:three:four:five:six:seven

one
two
three:four:five:six:seven


My current regex is just capturing each word separately, resulting in 4 matches

/(\s*\w+)/gi

Answer

The solution using String.match and Array.slice functions:

var str = "one:two:three:four:five:six:seven",
    groups = str.match(/([^:]+?):([^:]+?):(.+)?$/).slice(1);

console.log(groups);  // ["one", "two", "three:four:five:six:seven"]