简体   繁体   中英

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:

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM