javascript - 在 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 Document 的脚本编辑器中,并设置 searchPattern。并且,请在 Advanced Google services 中启用 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"}});
参考:
推荐阅读
- flutter - Flutter:sqflite批量插入大量数据冻结UI
- javascript - 为什么 if 条件中的代码即使不应该使用 react 和 javascript 也会执行?
- r - 将R中的表格按升序合并在一行中
- npm - 如何弃用发布到 GitHub 包注册表的 npm 包?
- android - Xamarin.Forms Tapped 事件,没有可绑定的属性
- nsis - NSIS 教程中的安装程序写入错误用户的桌面
- scala - Lagom Framework 手动 kafka 连接没有 kubernetes
- javascript - 更改字符串中的某些单词以突出显示(PHP)
- c# - 通过对象过滤时在 asp.net mvc 中保持模型状态
- javascript - Razorpay 结帐窗口未在 WordPress 中打开