【发布时间】:2017-04-16 12:23:27
【问题描述】:
这是一个简单的问题(我是 JavaScript 新手,对语法和使用数组等知识有限),所以我相信知识渊博的人将能够相当容易地提出最简单的解决方案!
我想用可变文本输入替换现有 Google Doc 模板中的一些文本占位符,我最终计划通过 API(例如表单)从一个或多个外部源填充这些文本。
function replaceAllPlaceholders() {
var body = DocumentApp.getActiveDocument().getBody(); //defines the range within which to replace text
body.replaceText('placeholder1', 'replacement1');
body.replaceText('placeholder2', 'replacement2');
body.replaceText('placeholder3', 'replacement3');
// ...
body.replaceText('placeholder98', 'replacement98');
body.replaceText('placeholder99', 'replacement99'); }
不是像我在上面所做的那样为每个替换重复 replaceText( 函数,而是如何将信息布局为一个占位符数组:替换对,然后循环遍历每个?
// for example something like this (pseudo):
//
// var obj = {
// 'placeholder1': 'replacement1' // I would like to keep open the option to retrieve this array from an external source instead
// 'placeholder2': 'replacement2'
// 'placeholder3': 'replacement3' };
//
// body.replaceText(*all placeholders*,*all replacements*);
我想这将允许在编辑一组占位符和/或替换时有更大的灵活性,无论是直接在 Google Apps 脚本中还是通过将整个数组替换为从外部源检索的一个(以及减少所需的代码) .问题是我无法找出正确的方法来做到这一点。有什么建议吗?
或者,有没有更好的方法来实现我的目标? 我愿意接受所有建议!
【问题讨论】:
标签: javascript arrays replace google-apps-script google-docs-api