我需要在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文档的脚本编辑器中,然后设置searchPattern。并且,请在高级Google服务中启用Google Docs API。
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);
}
使用上述脚本时,可获得以下结果。
从: 至:如果您不想像上一个问题那样直接使用高级Google服务,请按如下所示修改https://stackoverflow.com/a/65745933的第二个脚本。
从
ar.push({insertPageBreak: {location: {index: p.index + offset}}});
至
ar.push({insertText: {location: {index: p.index + offset},text: "\n"}});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句