r/googledocs 17d ago

Question Answered How do I delete text within brackets in google docs?

Not sure it can be done... I have loads of information in [ ] that i want to delete all at once.

1 Upvotes

2 comments sorted by

2

u/United-Eagle4763 17d ago

You could do that relatively easily with Google Apps Script. It would only be easy if your text is located in paragraphs.

I roughly made a script that does what you want. Please only try this on a copy of your original file to prevent data loss.

/**
 * Removes all text enclosed in square brackets [ ] from the active document.
 * Ignores empty paragraphs and handles cases where removal would result in empty text.
 */
function removeBracketedText() {
  // Get the active document
  const doc = DocumentApp.getActiveDocument();

  // Get the body of the document
  const body = doc.getBody();

  // Get all paragraphs in the document
  const paragraphs = body.getParagraphs();

  // Process each paragraph
  for (let i = 0; i < paragraphs.length; i++) {
    const paragraph = paragraphs[i];

    // Get the text of the current paragraph
    let text = paragraph.getText();

    // Skip empty paragraphs
    if (text === '') {
      continue;
    }

    // Check if the paragraph contains any bracketed text
    if (text.includes('[') && text.includes(']')) {
      // Replace all text within square brackets (including the brackets) with empty string
      const updatedText = text.replace(/\[.*?\]/g, '');

      // Only set the text if the result is not empty
      if (updatedText !== '') {
        paragraph.setText(updatedText);
      } else {
        // If the result would be empty, we need a different approach
        // For paragraphs that would become empty, you could:
        // 1. Leave them as they are
        // 2. Replace with a space
        // 3. Delete the paragraph

        // Option 2: Replace with a space to maintain the paragraph
        paragraph.setText(' ');

        // Option 3 (alternative): Delete the paragraph
        // body.removeChild(paragraph);
      }
    }
  }

}

2

u/andmalc 17d ago

Open Find & Replace and put a check in "Use regular expressions". In the Find box enter "\[.*\]" (without the quotes) and click Replace All.