Google Apps Script that removes elements starting with a number and also trims any leading whitespace from the start of each element in a Google Docs document

To create a Google Apps Script that removes elements starting with a number and also trims any leading whitespace from the start of each element in a Google Docs document, we’ll focus on text elements within paragraphs. The script below iterates through all paragraph elements, checks if they start with a number, and then performs the necessary modifications.

This script will:

  1. Remove the leading numbers and any following punctuation (like a period or colon) and whitespace at the beginning of each paragraph element.
  2. Strip additional whitespace from the start of the modified text.

Here’s how you can write the script:

function removeNumberPrefixAndTrim() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();

  paragraphs.forEach(function(paragraph) {
    var text = paragraph.getText();
    // Regular expression to match text starting with a number, possibly followed by punctuation and whitespace
    var updatedText = text.replace(/^\d+[\.\:]\s*/, '').replace(/^\d+\s*/, '');

    // Trim leading whitespace from the updated text
    updatedText = updatedText.trim();

    // Check if the updated text is not empty before setting it
    if (updatedText !== '') {
      paragraph.setText(updatedText);
    } else {
      // Optionally handle empty paragraphs, e.g., by deleting them or leaving as is
      // paragraph.removeFromParent(); // Uncomment to delete empty paragraphs
    }
  });
}

This script works as follows:

  • It iterates through each paragraph in the document.
  • Uses regular expressions to remove any leading numbers followed by an optional period or colon and any spaces immediately after them. It first tries to remove numbers followed by a punctuation mark and space, then removes numbers followed by spaces, covering both cases where the number might be part of a list or simply a number at the start.
  • Trims any remaining leading whitespace from the text.
  • Sets the updated text back to the paragraph, ensuring that elements starting with numbers are modified according to your specifications.

To use this script:

  1. Open your Google Docs document.
  2. Click on Extensions -> Apps Script.
  3. Delete any code in the script editor and paste the above script.
  4. Save the script with a name, e.g., RemoveNumberPrefixAndTrim.
  5. Run the script by clicking the play/run button. You might need to authorize the script to run under your Google account the first time.

This script can be customized further based on specific needs, such as handling different types of elements (not just paragraphs) or applying different text modifications.