Alex Rivera | Logout

How to capture an arbitrary number of groups in JavaScript Regexp?

Asked 2010-08-21T14:08:24.800
99

I would expect this line of JavaScript:

"foo bar baz".match(/^(\s*\w+)+$/)

to return something like:

["foo bar baz", "foo", " bar", " baz"]

but instead it returns only the last captured match:

["foo bar baz", " baz"]

Is there a way to get all the captured matches?

Edit
Report

1 Answer

6

Unless you have a more complicated requirement for how you're splitting your strings, you can split them, and then return the initial string with them:

var data = "foo bar baz";
var pieces = data.split(' ');
pieces.unshift(data);
answered 2010-08-21T14:22:30.333

Your Answer