Remove a pattern on mulitple lines using Apps Script

function removeTextPatternWithLineBreaks() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const paragraphs = body.getParagraphs();

  paragraphs.forEach(paragraph => {
    const text = paragraph.getText();

    // Adjust pattern to handle line breaks (Shift+Enter in Docs)
    const pattern = /javascript\s+copy code/gi;

    // Check if the pattern exists in the paragraph
    if (pattern.test(text)) {
      // Replace the matched pattern with an empty string
      const updatedText = text.replace(pattern, '');
      paragraph.setText(updatedText);
    }
  });

  Logger.log("Occurrences of the text pattern have been removed.");
}

Key Adjustments:

  1. Pattern Update:
    • \s+ matches one or more whitespace characters, including line breaks or spaces.
    • This works whether it’s a literal space, a line break (Shift+Enter), or a combination.
  2. Global and Case-Insensitive Flags:
    • g ensures all occurrences in a paragraph are found.
    • i makes the search case-insensitive.

Testing and Usage:

  1. Add some test text in your Google Doc, such as:Copy code JavaScript Copy code
  2. Run this script to remove these occurrences.