Search code examples
google-docs-api

replaceText with square brackets in google script


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.


Solution

  • 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