Michalis
Michalis

Reputation: 6926

Javascript - Replace all with regex

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

Answers (3)

T.J. Crowder
T.J. Crowder

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

NullDev
NullDev

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

Wiktor Stribiżew
Wiktor Stribiżew

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); // => ))))))

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).

Upvotes: 1

Related Questions