Replace spaces, but not when between parentheses

I think I can do this with a few regular expressions quite easily, but I want to replace all the spaces in the string, but not when these spaces are between the parentheses.

For instance:

Here is a string (that I want to) replace spaces in.

After regex, I want the string to be

Hereisastring(that I want to)replacespacesin.

Is there an easy way to do this with lookahead or lookbehing?

I am a bit confused about how they work, and not sure if they will work in this situation.

+5
source share
1 answer

Try the following:

replace(/\s+(?=[^()]*(\(|$))/g, '')

Brief explanation:

\s+          # one or more white-space chars
(?=          # start positive look ahead
  [^()]*     #   zero or more chars other than '(' and ')'
  (          #   start group 1
    \(       #     a '('
    |        #     OR
    $        #     the end of input
  )          #   end group 1
)            # end positive look ahead

: , (, , .

- Ideone: http://ideone.com/jaljw

, :

+9

All Articles