App Script Google Docs替换正文

时间:2018-12-22 01:15:24

标签: google-apps-script google-docs

我在使用App脚本替换Google文档中的文本时遇到了麻烦。

在文档中,我有某些标记/令牌,例如${TOKEN.SUBTOKEN}。我以文本形式获取文档,并使用正则表达式将所有 TOKEN 提取为列表,没有问题,但是当我想使用replaceText函数时,我遇到了问题。当我执行replaceText行时,它不会更改文档中的值,而是返回文档中的元素。我找不到替换我定位的文本的方法。

var doc = DocumentApp.openById(docId);
var docBody = doc.getBody();
// tokenValues is the Object that contains the values to replace. 
var fields = docBody.getText().match(/\$\{[a-z0-9\.\_]+\}/gi);
  for (var i = 0; i < fields.length; i++ ) {
    fields[i] = fields[i].substring(2, fields[i].length-1);
  }
for (var i; i < fields.length; i++) {
    Logger.log(docBody.replaceText(new RegExp('\\${ *' +  fields[i].replace('/\./g', '\.') + '\ *}', tokenValues[i]));
}

我应该如何处理这个问题,因为文档不够明确(或者我可能不理解),所以遇到了问题

1 个答案:

答案 0 :(得分:1)

我做了与您的问题类似的事情。

以下是文字:

{{ClientName}} would like to have a {{Product}} {{done/created}}. The purpose of this {{Product}} is to {{ProductPurpose}}. We have experience with such testing and development, and will develop and test the {{Product}} for {{ClientName}}.

代码如下:

function searchReplace(){
  var regex1=new RegExp('{{([a-zA-Z/]+)}}','g');
  var tA=[];
  var srchA=[];
  var fldA=[];
  var s=DocumentApp.getActiveDocument().getBody().getText();
  while((tA=regex1.exec(s))!==null){//get all fields
    fldA.push(tA[1]);
  }
  for(var i=0;i<fldA.length;i++){//Get unique fields
    if(srchA.indexOf(fldA[i])==-1){
      srchA.push(fldA[i]);
    }
  }
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  for(var i=0;i<srchA.length;i++){
    var searchPattern=Utilities.formatString('\\{\\{(%s)\\}\\}', srchA[i]);//need double backslashes here.
    var prompt=Utilities.formatString('Enter Replacement for %s',srchA[i]); 
    var resp=DocumentApp.getUi().prompt('Replacement Text',prompt , DocumentApp.getUi().ButtonSet.OK_CANCEL)
    if(resp.getSelectedButton()==DocumentApp.getUi().Button.OK){
      body.replaceText(searchPattern, resp.getResponseText());//replaces all instances of the field
    }
  }
}
相关问题