5

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
 }

1 Answer 1

3

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".

1
  • Thanks! This is exactly what I needed, but couldn't do on my own. And thanks especially for the explanation on the regular expression, as I could not understand it without the details you provided. Jan 12, 2018 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.