Moddinu
Moddinu

Reputation: 185

Javascript Split text by space but ignore spaces in brackets

I am using the following regex :

Let say the value is Matthew Smith (Is a Builder)

this.value.match(/(\([^\)]+\)|\S+)/g);

This return [Matthew],[Smith], [(Is a Builder)].

I would like to return [Matthew],[" "],[Smith],[" "],[(Is a Builder)]. Can any body help out?

Upvotes: 0

Views: 595

Answers (2)

John Bupit
John Bupit

Reputation: 10618

Try this:

/(\(.*\)|\S+|\s+)/
  • \(.*\) matches the strings of form (any character (even nested brackets) inside)

  • \S+ matches any string of non-white space character

  • \s+ matches any string white space character

Example input:

Matthew Smith (Is a Builder)

Matthew Smith (Is a (very good) Builder)

Example output:

[Matthew], [" "], [Smith], [" "], [(Is a Builder)]

[Matthew], [" "], [Smith], [" "], [(Is a (very good) Builder)]

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

Also add \s+ to the alternations.

/(\([^\)]+\)|\S+|\s+)/

Upvotes: 2

Related Questions