replaceText with square brackets in google script

1.4k views Asked by At

I am building a mail merge type function in google docs scripts. I have chosen to use square brackets to delimit the fields. I have noticed replaceText does strange things when matching for strings with square brackets, as demonstrated by the following test function.

function testReplace()
{
  var outputDoc = DocumentApp.create("testReplace");
  outputDoc.appendParagraph('Hello [World]');
  var body = outputDoc.getActiveSection();
  body.replaceText('[World]', 'There');
  // Document content:
  // HeThereThereThere [ThereThereThereThereThere]
  // I would have expected:
  // Hello There
}

Can anyone explain what is going on? Thanks in Advance.

2

There are 2 answers

2
StephenTG On BEST ANSWER

You're replacing every occurrence of 'W','o','r','l', or 'd' with 'There'

[xyz] matches 'x', 'y', or 'z', not 'xyz'.

You need to escape the square brackets. Try "\[World\]"

Here's an answer with a basic primer on how to use regular expressions

1
avch On

I had the same issue, Use slash twise, this solved my issue.