简体   繁体   中英

How to remove text from Google Docs using App Scripts?

I just recently built a series of documents using Google Script and Form/Sheets.

The document generates in Google Docs via the script, using the data provided in the initial form.

The setup is basically as below:

Conditions to pass

  • Class: {{CLASS}}
  • Minimum Grade: {{MINIMUM_GRADE}} / 10
  • Minimum attendance: {{ATTENDANCE_PERC}}% with a minimum of {{ATTENDANCE}} attendances over the semester

Where the form input is placed between those {{ }}.

Currently , this case would show something like:

  • Class: 3rd Year
  • Minimum Grade: Not Applicable / 10
  • Minimum attendance: 70% with a minimum of 15 attendances over the semester

But I would like:

  • Class: 3rd Year
  • Minimum attendance: 70% with a minimum of 15 attendances over the semester

Is there any way that I can make Google Script automatically remove, any of the the bullet point, for example here "Minimum Grade" if the answer to this question is "Not Applicable"?

Answer:

You can get all children of the Document, and remove the child from the body if the Element object is a LIST_ITEM and the Element object contains the text "Not Applicable".

More Information:

The structure of a Document is quite tricky, but knowing that a given child is a LIST_ITEM Element type, you can check to see if it contains the text you require and subsequently remove the child from the body of the Document.

Code:

function removeListItem() {
  var body = DocumentApp.getActiveDocument().getBody();
  var noOfChildren = body.getNumChildren();
  var childrenToRemove = [];
  
  for (var i = 0; i < noOfChildren; i++) {
    var child = body.getChild(i);
    var childType = child.getType();
    if (childType == DocumentApp.ElementType.LIST_ITEM) {
      if (child.asListItem().findText("Not Applicable") !== null ) {
        childrenToRemove.push(child); 
      }
    }
  }
  
  childrenToRemove.forEach(function(child) {
    try {
      body.removeChild(child);
    }
    catch(e) {
      Logger.log(e)
      if (e == "Exception: Can't remove the last paragraph in a document section.") {
        body.appendPageBreak()
        body.removeChild(child);
      }
    }
  });
}

I hope this is helpful to you!

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM