hunter21188
hunter21188

Reputation: 415

Use RegEx in Google Doc Apps Script to Replace Text

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!

Upvotes: 2

Views: 4698

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

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.

Upvotes: 3

Related Questions