在Google Apps脚本中的文本前插入换行符 [英] Insert Line breaks before text in Google Apps Script

查看:33
本文介绍了在Google Apps脚本中的文本前插入换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Google文档中的某些文本之前插入一些换行符。

尝试此方法但遇到错误:

var body = DocumentApp.getActiveDocument().getBody();
var pattern = "WORD 1";
var found = body.findText(pattern);
var parent = found.getElement().getParent();
var index = body.getChildIndex(parent);
// or parent.getChildIndex(parent);
body.insertParagraph(index, "");

有什么办法吗?

感谢您的帮助!

推荐答案

例如,作为一个简单的修改,修改您上一个问题中https://stackoverflow.com/a/65745933的脚本如何?

在这种情况下,使用InsertTextRequest而不是InsertPageBreakRequest.

修改后的脚本:

请将以下脚本复制粘贴到Google文档的脚本编辑器中,并设置搜索模式。和,please enable Google Docs API at Advanced Google services

function myFunction() {
  const searchText = "WORD 1";  // Please set text. This script inserts the pagebreak before this text.
  
  // 1. Retrieve all contents from Google Document using the method of "documents.get" in Docs API.
  const docId = DocumentApp.getActiveDocument().getId();
  const res = Docs.Documents.get(docId);
  
  // 2. Create the request body for using the method of "documents.batchUpdate" in Docs API.
  let offset = 0;
  const requests = res.body.content.reduce((ar, e) => {
    if (e.paragraph) {
      e.paragraph.elements.forEach(f => {
        if (f.textRun) {
          const re = new RegExp(searchText, "g");
          let p = null;
          while (p = re.exec(f.textRun.content)) {
            ar.push({insertText: {location: {index: p.index + offset},text: "
"}});
          }
        }
      })
    }
    offset = e.endIndex;
    return ar;
  }, []).reverse();
  
  // 3. Request the request body to the method of "documents.batchUpdate" in Docs API.
  Docs.Documents.batchUpdate({requests: requests}, docId);
}

结果:

使用上述脚本时,会得到以下结果。

出发地:

致:

注意:

  • 当您不想像上一个问题那样直接使用高级Google服务时,请修改https://stackoverflow.com/a/65745933的第二个脚本,如下所示。

    • 发件人

        ar.push({insertPageBreak: {location: {index: p.index + offset}}});
      
    •   ar.push({insertText: {location: {index: p.index + offset},text: "
      "}});
      

引用:

这篇关于在Google Apps脚本中的文本前插入换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆