1

I want to replace some spaces between some parenthesis with regex. If I use regex only replace some spaces (only unique pairs).

The string may be have others spaces, but I want only the spaces between paranthesis.

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s\)/g, "))");
console.log(mystring);

Output is:

) ) ) ) ) )
)) )) ))

But I want to have this output:

) ) ) ) ) )
))))))
0

3 Answers 3

9

The problem is that by consuming the ) ), you no longer have the leading ) when looking at the next part of the string.

Instead of replacing both ), use a positive lookahead assertion to replace only the first and the spaces after it if they're followed by another ):

mystring = mystring.replace(/\)\s(?=\))/g, ")");
//                  Lookahead ---^^^^^^     ^--- only one ) in replacement

Live Example:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s(?=\))/g, ")");
console.log(mystring);

Sign up to request clarification or add additional context in comments.

Comments

2

How about a lookbehind:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/(?<=\))\s(?=\))/g, "");
console.log(mystring);

Demo:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/(?<=\))\s(?=\))/g, "");
console.log(mystring);

This will remove all spaces between ) )

1 Comment

Lookbehind is, of course, brand-new in JavaScript and not in spec yet (it's still a Stage 3 proposal), so one would need to be careful about whether it was supported in the target browsers. (Whereas lookahead has been there since the 3rd edition spec, 1999.) No need for lookbehind in this case.
1

Move the last ) to a positive lookahead and replace with a single ):

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s+(?=\))/g, ")");
console.log(mystring); // => ))))))

See the regex demo.

Pattern details

  • \) - a )
  • \s+ - 1+ whitespaces
  • (?=\)) - a positive lookahead that requires a ) immediately to the right of the current location (after 1+ whitespaces).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.