1

I have searched and searched for the answer to this but no luck. Am trying to replace text from a doc using doc.replaceText(). (Referring to the same tutorial on sending emails from spreadsheets). Whatever I may try, %, #, or any other special characters, my string does not get replaced. Any help would be appreciated.

Here's my code snippet:

function createHtmlMessage(gradesList) 
{

  var templateDocId = ScriptProperties.getProperty("EmailTemplateDoc");
  var docId = DocsList.getFileById(templateDocId).makeCopy().getId();
  var doc = DocumentApp.openById(docId);
  var body = doc.getActiveSection();
  var html = "";

  var keys = {
      STUDENT_NAME: "student",
      GR_ENGLISH: gradesList[0],
      GR_MATHS: gradesList[1],
      GR_SCIENCE: gradesList[2],
      GR_SOCIAL: gradesList[3],
      GR_2NDLANG: gradesList[4],
      GR_3RDLANG: gradesList[5],
      GR_COMPUTERS: gradesList[6],
      REMARKS: "remarks"
  };


  for ( var k in keys ){
     var source = k;
     var dest = keys[k];
     body.replaceText("%" + k + "%", keys[k]);
  }
  html = getDocAsHtml(docId);

  DocsList.getFileById(docId).setTrashed(true);
  return html;
}

All my 'keys' are present in the document with a preceeding and following "%" sign.

3 Answers3

1

I see that you trash the document after making the changes. Not sure of the purpose In any case, you should try Document.saveAndClose() after you make your changes.

Srik
  • 7,907
  • 2
  • 20
  • 29
0

You need to save the document before getting it as HTML

for ( var k in keys ){
     var source = k;
     var dest = keys[k];
     body.replaceText("%" + k + "%", keys[k]);
  }
doc.saveAndClose();
html = getDocAsHtml(docId);
Waqar Ahmad
  • 3,716
  • 1
  • 16
  • 27
0

Did you see this post that was on the very same subject ?

Also, I'm not sure about what Srik said about saving since we don't know what is in your getDocAsHtml(docId) function .... maybe you could post that part too ?

EDIT : I just tested your code and the replace part works as expected... I suspect the problem is in the conversion to html. You should keep the doc you trash to see if this one is ok.

Community
  • 1
  • 1
Serge insas
  • 45,904
  • 7
  • 105
  • 131