使用GAS 参考文献:

问题描述

我想将段落更改为列出以##开头的段落的类型。

文档文档为here

我尝试过

function doGet(e) {
    var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1TRo9RG6R2ZOBqXQEJtBhRBLKzu9XOlFycamYplkma14/edit');
    var body = doc.getBody();
    var paras = body.getParagraphs();
    for (var i = 0; i < paras.length; i++) {
        if (paras[i].editAsText().getText().indexOf("##") == 0) {
            //var listItem = body.insertListItem(childindex,listItem)
            var text = paras[i].editAsText().getText()
            var childindex = body.getChildindex(paras[i])
            var element = body.removeChild(paras[i])
            element.appendListItem(text).setGlyphType(DocumentApp.GlyphType.BULLET)
        }
    }
    return ContentService.createtextoutput("Success" + body.getChildindex(paras[3]));
}

解决方法

您快到了。但是我会看的是Body.insertListItem()方法,而不是Body.appendListItem()方法。

例如,您可以将for循环更改为以下内容:

for (var i = 0; i < paras.length; i++) {
  if (paras[i].editAsText().getText().indexOf("##") == 0) {
    // This element is a future list item
    var elem = paras[i];
    // What's the text going to be?
    var text = elem.editAsText().getText()
    // Where will it be inserted?
    var childIndex = body.getChildIndex(elem)
    // I should remove the old element
    body.removeChild(elem)
    // And take it's place with this new one with Glyph.
    body.insertListItem(childIndex,text).setGlyphType(DocumentApp.GlyphType.BULLET)
  }
}

参考文献: