Kon*_*ool 5 google-docs-api google-apps-script
我想使用 google appscript 替换我的 google 文档上的文本以将其转换为 PDF。但问题是函数 replaceText(textToReplace, newText); 只需删除匹配文本的每个匹配项。我只想删除第一次出现。怎么做?
小智 6
通过在该元素上调用该replaceText方法,可以将该方法的范围限制为该元素。但是,如果找到文本的第一段包含该文本的多个实例,则这无济于事:它们都将被替换。
相反,使用findText查找第一个匹配项,然后调用deleteText和insertText执行替换。
// replaces the first occurrence of old
function replaceFirst(old, replacement) {
var body = DocumentApp.getActiveDocument().getBody();
var found = body.findText(old);
if (found) {
var start = found.getStartOffset();
var end = found.getEndOffsetInclusive();
var text = found.getElement().asText();
text.deleteText(start, end);
text.insertText(start, replacement);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您认为这应该更容易,那么您并不孤单。