简体   繁体   中英

Insert Line breaks before text in Google Apps Script

I need to insert some line breaks before certain text in a Google Document.

Tried this approach but get errors:

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, "");

Any idea on how to do this?

Appreciate the help!

For example, as a simple modification, how about modifying the script of https://stackoverflow.com/a/65745933 in your previous question?

In this case, InsertTextRequest is used instead of InsertPageBreakRequest.

Modified script:

Please copy and paste the following script to the script editor of Google Document, and please set searchPattern. And, 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: "\n"}});
          }
        }
      })
    }
    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);
}

Result:

When above script is used, the following result is obtained.

From:

在此处输入图像描述

To:

在此处输入图像描述

Note:

  • When you don't want to directly use Advanced Google services like your previous question, please modify the 2nd script of https://stackoverflow.com/a/65745933 is as follows.

    • From

       ar.push({insertPageBreak: {location: {index: p.index + offset}}});
    • To

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

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