我正在尝试用此文本的脚注替换与特定正则表达式匹配的文本。
我知道如何找到正则表达式的每次出现(感谢这里的其他帖子)
我知道如何使用 API 创建脚注(感谢 here 的问题)
我想,我什至知道如何将文本放入与创建的脚注对应的脚注部分
但是我需要文本中位置的索引,并且我的搜索(通过脚本完成,而不是通过请求完成)返回“元素”中的一些抽象起始位置,这不是文档正文开头的索引(它是api 想要什么)。
哪里可以获得索引?
function makeRef() {
var body = DocumentApp.getActiveDocument().getBody()
const documentId = DocumentApp.getActiveDocument().getId();
var myRegEx = '\\([a-z,A-Z]+?.+?,.+?[12][0-9][0-9][0-9]\\)'
var foundElement = body.findText(myRegEx);
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the Element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
var requests = [
{
createFootnote: {
location: {
index: start
}
}
}]
Docs.Documents.batchUpdate({requests:requests},documentId)
// Find the next match
foundElement = body.findText(myRegEx, foundElement);
}
}
问题是:如何获取需要脚注的地方的索引?
我相信您的目标如下。
Harry Potter is a magical child (Rowling, 1996)
修改为 Harry Potter is a magical child^1
,并且想要将 ^1 Rowling, 1996
作为脚注。在这种情况下,下面的示例脚本怎么样?
我认为从您的展示脚本中直接获取使用Docs API的索引可能会很困难。那么,为了获取索引,使用Docs API怎么样?根据您的情况,以下示例脚本怎么样?
请将以下脚本复制并粘贴到 Google 文档的脚本编辑器中,并在高级 Google 服务中启用 Docs API。 参考
function myFunction() {
const myRegEx = '\\([a-z,A-Z]+?.+?,.+?[12][0-9][0-9][0-9]\\)'; // This is from your script.
// Retrieve the initial object from Google Document.
const documentId = DocumentApp.getActiveDocument().getId();
const obj1 = Docs.Documents.get(documentId).body.content;
// Retrieving texts and creating footnotes.
const r = new RegExp(myRegEx, "g");
const { requests1, texts } = obj1.reduce((o, e) => {
if (e.paragraph) {
e.paragraph.elements.forEach(f => {
if (f.textRun) {
const m = [...f.textRun.content.matchAll(r)];
if (m.length > 0) {
m.forEach(c => {
o.texts.push(c[0]);
o.requests1.push({ createFootnote: { location: { index: e.startIndex + c.index - 1 } } });
o.requests1.push({ deleteContentRange: { range: { startIndex: e.startIndex + c.index, endIndex: e.startIndex + c.index + c[0].length } } });
});
}
}
});
}
return o;
}, { requests1: [], texts: [] });
const { replies } = Docs.Documents.batchUpdate({ requests: requests1.reverse() }, documentId);
const footnoteIds = replies.reduce((ar, e) => {
if (e && e.createFootnote && e.createFootnote.footnoteId) {
ar.push(e.createFootnote.footnoteId)
}
return ar;
}, []).reverse();
// Retrieve the object after footnotes were created.
const { footnotes } = Docs.Documents.get(documentId);
// Inserting texts to footnotes.
const requests2 = footnoteIds.reduce((ar, id, i) => {
const o = footnotes[id]
if (o) {
ar.push({ insertText: { location: { segmentId: id, index: o.content[0].endIndex - 1 }, text: texts[i].replace(/\(|\)/g, "") } });
}
return ar;
}, []);
Docs.Documents.batchUpdate({ requests: requests2 }, documentId);
}
当此脚本运行到您提供的示例 Google 文档时,将获得以下结果。