Search code examples
javascriptregexparentheses

remove empty parenthesis from expression


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 ?


Solution

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