您可以使用NamedRanges來實現此類效果。基本上,策略是:
- 添加你的文字,段落或其他文檔元素
- 裹在文檔NamedRange
- 記錄的NamedRange ID的文本,並將其與你需要的任何其他數據相關聯附加到特定的文本(例如插入時間或自定義屬性,或其他)。
- 稍後,當您需要查找文本(或只是確定它是否存在)時,可以查詢NamedRange ID的列表,然後使用該ID引用文檔中的文本。
這裏有一個粗略的實施這種戰略的:
function testing() {
// Add a new paragraph within a Named Range
var named = addTextWithNamedRange('This is my added text', 'RangeLabel01');
// NamedRanges can share the same names, but the IDs are unique,
// so use IDs to easily reference specific NamedRanges
var namedId = named.getId();
// Now save this ID to a data structure, along with any other information
// about it you need to record
// Later, when you need to reference that text/paragraph/element,
// use the ID to find it, and make any changes you need:
accessNamedRange(namedId);
}
function addTextWithNamedRange(str, name) {
// Add a new paragraph to end of doc
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.appendParagraph(str);
// Creates a NamedRange that includes the new paragraph
// Return the created Named Range
var rangeBuilder = doc.newRange();
rangeBuilder.addElement(text);
return doc.addNamedRange(name, rangeBuilder.build());
}
function accessNamedRange(rangeId) {
// Determine if a NamedRange with this ID exists
// If it does, log information about it and the Paragraph
// elements it includes
var doc = DocumentApp.getActiveDocument();
var named = doc.getNamedRangeById(rangeId);
if (named) {
var rangeElements = named.getRange().getRangeElements();
for(var r in rangeElements) {
var text = rangeElements[r].getElement().asParagraph().getText();
// Just logging here, but could potentially edit or
// otherwise manipulate the text
Logger.log('Found NamedRange ' + named.getName() +
' (id='+rangeId+') --> ' + text);
}
}
}