-1

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.

starry.au
  • 13
  • 2

2 Answers2

0

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

Community
  • 1
  • 1
StephenTG
  • 2,579
  • 6
  • 26
  • 36
  • Thanks for setting me straight on this. – starry.au Jun 25 '15 at 12:14
  • @starry.au Glad I could help – StephenTG Jun 25 '15 at 12:15
  • Thanks for the explanation i did not realize this parameter was a regular expression, I can see form the output that this is how the parameter is being interpreted. However, when I included the escaped match string "\[WORLD\]" I get the same result. Can you recommend an alternative way to escape the brackets. – starry.au Jun 26 '15 at 10:35
0

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

avch
  • 19
  • 1
  • 3