Remove numbers at the start of a heading or any page element in Google Docs Google Apps Script Code

You can create a Google Apps Script to remove the first numbers up to the first period in Google Docs from all page elements if the element begins with a number. Here’s a sample script that you can use:

function removeNumbersFromPageElements() {
   const doc = DocumentApp.getActiveDocument();
    const body = doc.getBody();
  const elements = body.getParagraphs();


  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    var text = element.getText();
    
    // Check if the text starts with a number
    if (/^\d/.test(text)) {
      // Find the index of the first period (.)
      var periodIndex = text.indexOf('.');
      
      // Remove the numbers up to the first period
      if (periodIndex !== -1) {
        var newText = text.substring(periodIndex + 1);
        element.setText(newText);
      }
    }
  }
}

Here’s how to use the script:

  1. Open your Google Docs document.
  2. Click on Extensions in the menu bar.
  3. Select Apps Script.
  4. Replace any existing code in the script editor with the provided code.
  5. Save the script and give it a name.
  6. Run the script by clicking the play button (▶) in the toolbar.

The script will go through all the text elements in your document and remove the first numbers up to the first period if the text element starts with a number.

Google Apps Script for a Google Docs document that finds all H3 elements

You can create a Google Apps Script for a Google Docs document that finds all H3 elements and checks if they start with a number. If they do, it will remove the number up to and including the following period and update the page element accordingly. Here’s a script to achieve this:

function removeNumbersFromH3Elements() {
  var body = DocumentApp.getActiveDocument().getBody();
  var elements = body.getParagraphs();
  
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    var text = element.getText();
    
    // Check if the element is an H3 and starts with a number
    if (element.getHeading() == DocumentApp.ParagraphHeading.HEADING3 && /^\d+\./.test(text)) {
      // Remove the number up to and including the following period
      var newText = text.replace(/^\d+\./, '');
      element.setText(newText);
    }
  }
}

Here’s how to use the script:

  1. Open your Google Docs document.
  2. Click on Extensions in the menu bar.
  3. Select Apps Script.
  4. Replace any existing code in the script editor with the provided code.
  5. Save the script and give it a name.
  6. Run the script by clicking the play button (▶) in the toolbar.

The script will go through all H3 elements in your document and remove the number up to and including the following period if the element starts with a number.