title: App Script Google Docs Replace Text in Body
body: <p>I'm having trouble, replacing text in a Google Doc, using App Script. </p>
  
  <p>Inside the document I have certain tags/tokens like <code>${TOKEN.SUBTOKEN}</code>. I get the document as text and extract all the <em>TOKEN</em>'s as a list with a Regex without issue, but when I want to use the <code>replaceText</code> function, I have issues. When I execute the <code>replaceText</code> 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. </p>
  
  <pre><code>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 &lt; fields.length; i++ ) {
      fields[i] = fields[i].substring(2, fields[i].length-1);
    }
  for (var i; i &lt; fields.length; i++) {
      Logger.log(docBody.replaceText(new RegExp('\\${ *' +  fields[i].replace('/\./g', '\.') + '\ *}', tokenValues[i]));
  }
  </code></pre>
  
  <p>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) </p>