0
votes

I have a google doc with placeholders in it that need to be filled with actual data using Apps Script. e.g. of the Google Doc content:

This is template text. Replace this {TOKEN1} and this {TOKEN2} and this {TOKEN3} as well using Google Apps Script.

The requirement is to replace the tokens and repeat this paragraph multiple times. Each time the paragraph is replaced, a different set of values needs to be placed in the paragraph. The formatting should not be broken, in this case, the tokens were in bold hence the values also should be in bold as below:

This is template text. Replace this FOO1 and this BAR1 and this FUN1 as well using Google Apps Script.

This is template text. Replace this FOO2 and this BAR2 and this FUN2 as well using Google Apps Script.

This is template text. Replace this FOO3 and this BAR3 and this FUN3 as well using Google Apps Script.

Could you let me know the Apps script approach to achieve this functionality?

1
to make a valid question show your coding attempts and whats not working. so far its just a specification. - Zig Mandel

1 Answers

0
votes

I was able to achieve the requirement as below:

  1. Iterate through all the elements in the document and process paragraphs:

    var elementCount = body.getNumChildren();
    for(var i = 0; i < elementCount; i++) {
      var child = body.getChild(i);
      if(child.getType() === DocumentApp.ElementType.PARAGRAPH) {
        replaceTokensInParagraph(element.asParagraph(), i);
      }  
    }
    
  2. Collect all the tokens from the paragraph text

  3. Remove the paragraph from the doc as we don't need the templated paragraph in the final document

  4. Make a detached copy of the templated paragraph

  5. Replace tokens in the detached copy

Overall, the function looks as below:

var replaceTokensInParagraph = function(paragraph, paragraphIndex) {
  paragraph.removeFromParent();
  var tokens = ....;
  for(int i=0; i<tokens.length; i++) {
     var paragraphCopy = paragraph.copy();
     paragraphCopy.replaceText(token, <value>);
     body.insertParagraph(paragraphIndex, paragraphCopy);
  }
}