Search code examples
google-apps-scriptgoogle-docs

Google Script to delete all content in a Google Doc after a certain keyword


I have a Google Doc where I want to remove everything (including tables and horizontal lines) after a certain keyword, including the keyword itself. However, the script I have now isn't working correctly and I have no clue why. It's only removing a few paragraphs and not everything. Any insight?

function deleteContent() {
  var keyword = "%delete%";
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var found = false;
  
  for (var i = 0; i < body.getNumChildren(); i++) {
    var element = body.getChild(i);
    if (element.getType() == DocumentApp.ElementType.PARAGRAPH && element.asParagraph().getText() == keyword) {
      found = true;
      for (var j = i+1; j < body.getNumChildren(); j++) {
        body.getChild(j).removeFromParent();
      }
      break;
    }
  }
}


Solution

  • I believe your goal is as follows.

    • You want to delete all contents after a paragraph of %delete% in Google Documents.

    Modification points:

    • In your script, the child is deleted with the ascending order. In this case, the child index is confused. I thought that this might be the reason for your current issue.

    When this script is reflected in your script, how about the following modification?

    Modified script:

    function deleteContent() {
      var keyword = "%delete%";
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      var numChildren = body.getNumChildren();
      for (var i = 0; i < numChildren; i++) {
        var element = body.getChild(i);
        if (element.getType() == DocumentApp.ElementType.PARAGRAPH && element.asParagraph().getText() == keyword) {
          for (var j = numChildren - 2; j >= i; j--) { // Modified
            body.getChild(j).removeFromParent();
          }
          break;
        }
      }
    }
    
    • By the way, in the current stage, the last paragraph cannot be deleted using the Document service (DocumentApp). Ref Please be careful about this. By this, I used var j = body.getNumChildren() - 2 as the initial condition.

    • About How would you include also deleting the keyword?, I modified the above script. j >= i + 1 was modified to j >= i.

    Reference: