As vks points out, regular expressions cannot, strictly speaking, count. You can cancel pairs, as in Andris's answer , but as you can see, regular expressions get a little long when you cover all cases. An alternative is to combine a regular expression with a normal function:
function do_replacement(x) { return x.replace(/[+-]+/g, function (r) { return r.replace(/\+/g, '').length % 2? '-' : '+'; } ); }
This divides the task into two parts:
- Use regex to match any sequence
+ and - - In the replace function, remove
+ from the matched string and count the remaining characters (which, thanks to the original regular expression, can only be - s) - Return either
+ or - , depending on whether the count is even (i.e. length % 2 is zero) or odd
source share