在 google 脚本中用方括号替换文本

replaceText with square brackets in google script

我正在 google 文档脚本中构建邮件合并类型功能。我选择使用方括号来分隔字段。我注意到 replaceText 在匹配带有方括号的字符串时会做一些奇怪的事情,如以下测试函数所示。

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
}

谁能解释一下这是怎么回事?提前致谢。

您要将 'W'、'o'、'r'、'l' 或 'd' 的每个匹配项替换为 'There'

[xyz] 匹配 'x'、'y' 或 'z',而不是 'xyz'。

您需要转义方括号。尝试“\[世界\]”

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

我遇到了同样的问题,两次使用斜线,这解决了我的问题。