Insert Line breaks before text in Google Apps Script(在Google Apps脚本中的文本前插入换行符)
本文介绍了在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: " "}});
引用:
- Method: documents.get
- Method: documents.batchUpdate
- InsertTextRequest
这篇关于在Google Apps脚本中的文本前插入换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在Google Apps脚本中的文本前插入换行符
基础教程推荐
猜你喜欢
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
