Search code examples
javascriptregexp-replace

Removing text between parentheses but only at given conditions


I have the following sentence:

The quick brown fox jumps over the lazy dog (see Book 1). The quick brown fox jumps over the lazy dog (see above). The quick brown fox jumps over the lazy dog (see Book 2). The quick brown fox jumps over the lazy dog (see Book 3).

I need to remove text between parentheses - parentheses and outer whitespaces included - inside the sentence at the following conditions:

  • the text between parentheses contains the word Book;
  • the text between parentheses is not placed at the end of the sentence.

So that sentence should become:

The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog (see above). The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog (see Book 3).

I know this regex sentence.replace(/ *\([^)]*\) */g, ""); - but I don't know how to apply the above-mentioned conditions.


Solution

  • Another regex:

    const regex = /\s\([^)]*?Book.*?\)(?=.*\(.*?Book.*?\))/g

    In the form of JS example:

      const p = 'Text (see the Book "def"). Text (see above). Text (Book 2) with more text (Book 3).';
    
      console.log(p.replace(regex, ''));