如何使用应用程序脚本从 Google 文档中删除文本?

How to remove text from Google Docs using App Scripts?

我最近刚刚使用 Google 脚本和 Form/Sheets 构建了一系列文档。

文档通过脚本在 Google 文档中生成,使用初始表单中提供的数据。

设置基本如下:

通过条件

表单输入位于 {{ }} 之间的位置。

目前,这种情况会显示如下内容:

但我想:

有什么方法可以让 Google 脚本自动删除任何要点,例如这里 "Minimum Grade" 如果这个问题的答案是 "Not Applicable"?

答案:

您可以获得Document的所有子对象,如果Element对象是LIST_ITEM [=32,则将子对象从body中移除=]和 元素对象包含文本“不适用”。

更多信息:

Document 的结构非常棘手,但知道给定的子项是 LIST_ITEM 元素类型,您可以检查它是否包含您需要的文本,然后从正文中删除子项文档。

代码:

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);
      }
    }
  });
}

参考文献: