4

I've a string like this foo bar(5) baz(0, 3) and need to split it into its parts based on spaces between each. So the result needs to look like this: ['foo', 'bar(5)', 'baz(0, 3)'].

I tried something like this:

var str = 'foo bar(5) baz(0, 3)';
str.split(' '); // => ['foo', 'bar(5)', 'baz(0,', '3)']

As you can see the result is not what I expect... Any ideas how to split it correctly? I think it's a turn for the RegExp-gurus here...

Update

A simple way could be to replace all , with ,:

str.replace(/, /g, ',').split(' ');

But that doesn't look really pretty to me...

yckart
  • 32,460
  • 9
  • 122
  • 129

1 Answers1

5

You can use .match for this.

str.match(/\w+(\(.*?\))?/g)
=> ["foo", "bar(5)", "baz(0, 3)"]
Dogbert
  • 212,659
  • 41
  • 396
  • 397