0
votes

I'm having trouble, replacing text in a Google Doc, using App Script.

Inside the document I have certain tags/tokens like ${TOKEN.SUBTOKEN}. I get the document as text and extract all the TOKEN's as a list with a Regex without issue, but when I want to use the replaceText function, I have issues. When I execute the replaceText line, it doesn't change the value in the document, but returns an element from the document. I can't find a way to replace the text I'm targeting.

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]));
}

How should I approach this, I'm having trouble with It because the documentation is not that explicit, (or maybe I don't understand it)

1
What's the accepted parameter "type" for replaceText()? - TheMaster

1 Answers

2
votes

I did something similar to your question.

Here's the text:

{{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}}.

Here's the code:

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
    }
  }
}