用 Google AppScript 替换 Google 文档中的文字

Replacing words in Google Docs with Google AppScript

我想创建一个宏,它接受一组特定的字符,并将其替换为另一组字符。这最好在我打字时发生。如何在 Google AppScript 中编写此代码?

此外,我确实意识到这个问题与这个问题非常相似:auto find and replace in Google Docs App Script,但我希望它能够在另一个词中替换集合。

实时文本替换存在问题,因为它需要一种自动检测文档更改的方法。虽然电子表格支持 onEdit 触发器,但文档不支持。您可以模拟此行为,如 in this answer.

所示

如果不需要实时替换,您可以简单地编写一个函数来进行正则表达式替换,并将该函数添加到菜单中:

function replaceText(){
  var docBody = DocumentApp.getActiveDocument().getBody();
  docBody.replaceText('[Aa]pple','pear'); 
  //Will replace "apple", "Apple," "applesauce", "pineapple"
}

function onOpen(e){
  DocumentApp.getUi()
  .createMenu("Text Replacer")
  .addItem("Replace all Text", 'replaceText')
  .addToUi();
}

如需帮助编写正则表达式,see this document