Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace spaces but not when between parentheses

I guess I can do this with multiple regexs fairly easily, but I want to replace all the spaces in a string, but not when those spaces are between parentheses.

For example:

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

After the 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 operators?

I'm a little confused on how they work, and not real sure they would work in this situation.

like image 785
Senica Gonzalez Avatar asked Sep 27 '11 18:09

Senica Gonzalez


People also ask

How do you replace all spaces in a string?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace space with commas in a string?

javascript replace multiple spaces with single spacevar singleSpacesString=multiSpacesString. replace(/ +/g, ' ');//"I have some big spaces."


1 Answers

Try this:

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

A quick 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

In plain English: it matches one or more white space chars if either a ( or the end-of-input can be seen ahead without encountering any parenthesis in between.

An online Ideone demo: http://ideone.com/jaljw

The above will not work if:

  • there are nested parenthesis
  • parenthesis can be escaped
like image 174
Bart Kiers Avatar answered Oct 16 '22 08:10

Bart Kiers