Reputation: 6926
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:
) ) ) ) ) )
))))))
Upvotes: 1
Views: 77
Reputation: 1074495
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);
Upvotes: 9
Reputation: 7303
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 ) )
Upvotes: 2
Reputation: 626926
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); // => ))))))
Pattern details
\)
- a )
\s+
- 1+ whitespaces(?=\))
- a positive lookahead that requires a )
immediately to the right of the current location (after 1+ whitespaces).Upvotes: 1