Google Apps Script – How to Update Footer Date Without Clearing Contents

google docsgoogle-apps-script

This lovely bit of code for a Google Doc template I use, does exactly what I need it to do except it clears all of the content in my footer instead of just the date. Is there any way to get just the former date cleared and not the rest of my copy? I'm looking to automate my copyright data when a document is opened:

function onOpen() {
  var doc = DocumentApp.getActiveDocument();
  var footer = doc.getFooter();  //gets the footer
  footer.clear();  //clears all data in footer

  //Get date
  var date = new Date();
  var year = date.getFullYear();

  footer.appendParagraph(FullYear);  //adds date to footer
 }

Best Answer

This is basically what replaceText is for:

function onOpen() {
  var doc = DocumentApp.getActiveDocument();
  var footer = doc.getFooter();  //gets the footer
  var date = new Date();
  var year = date.getFullYear(); // gets the year
  footer.replaceText("\\b20\\d\\d\\b", year);  // replaces any 20xx by the year
}

The regular expression "\\b20\\d\\d\\b" is hard to read because of backslash escaping; it means \b20\d\d\b which matches word boundary \b follows by the characters 20, followed by any two digit characters (0-9), followed by word boundary. The word boundaries mean the replacement will not happen, say in "Coffeen, IL 62017".