I want to remove those parenthesis which are empty from expression in javascript regular expression. For e.g (() a and b) -> ( and b). It should also work for the case ( ( ( () ) )a and b) -> (a and b). Basicaly it should remove unnecessary parenthesis from expression. I am writng reguar expression
expression.replace(/(\s)/,'');
but this is not working. Can anyone help ?
You can use
const text = "( ( ( () ) )a and b)";
let output = text;
while (output != (output = output.replace(/\(\s*\)/g, "")));
console.log(output);
The /\(\s*\)/g regex matches all non-overlapping occurrences of
\( - a literal ( char\s* - zero or more whitespace chars\) - a literal ) char.The while (output != ...) loop makes sure the replacement occurs as many times as necessary to remove all substrings between open/close parentheses until no more matches are found.
There are different ways to do this, a simple, iterative one is to repeatedly remove emtpy parentheses (need to be escaped in regex!):
function remove_empty_parens(str) {
let new_str = str.replace(/\(\s*\)/, '');
return new_str == str ? str : remove_empty_parens(new_str);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With