2

There is a line in a Google Doc that has a time and date stamp. I have written the following code using a regex to replace that line with the current time/date, but I am not sure why this isn't working.

function UpdateDate() {

  var document = DocumentApp.getActiveDocument();
  var date = new Date();

  var regExp = /[0-9]{1,2}:[0-9]{2} [A-Z]{2} [A-Za-z]* [0-9]{1,2}, [0-9]{4}/;
  document.replaceText(regExp, Utilities.formatDate(date, 'America/Denver', 'h:mm a MMMM dd, yyyy'));

}

If I replace the "regExp" in the document.replaceText line with, for example, "3:43 PM January 22, 2019", the code correctly replaces that with the updated date/time, but it is not able to replace the matched regex. Any ideas? Thanks!

3
  • Can you indicate what language you're working in? Commented Jan 23, 2019 at 17:40
  • @joanis - I am in google scripts, so I am using javascript. Commented Jan 23, 2019 at 18:13
  • Use var regExp = "[0-9]{1,2}:[0-9]{2} [A-Z]{2} [A-Za-z]* [0-9]{1,2}, [0-9]{4}";, pass the regex pattern with a string literal. Commented Jan 23, 2019 at 18:41

1 Answer 1

3

You should pass the regex with the help of a string literal:

var regExp = "[0-9]{1,2}:[0-9]{2} [A-Z]{2} [A-Za-z]* [0-9]{1,2}, [0-9]{4}";

The replaceText documentation explains it:

The search pattern is passed as a string, not a JavaScript regular expression object. Because of this you'll need to escape any backslashes in the pattern.

This methods uses Google's RE2 regular expression library, which limits the supported syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thank you for answer and supporting documentation!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.