Search code examples
regexgoogle-apps-scriptescapinggoogle-docsre2

How to use string with regex metacharacters as regex in replaceText?


I have a bit of code that is searching a document for a tag and replacing it with a specific merge field. This code works fine until my tag has a | (pipe symbol) in it.

For some reason that makes the search only partially match. I suspect this has something to do with it thinking the variable I am passing is a regEx pattern and not a literal string, but I am unsure how to force it to be treated as a string. I use replaceText, which accepts regex as a string.

bodyObject.replaceText(Regex<String>, Replacement<String>);

I use it like this:

bodyObject.replaceText(markup, dataRow[headerIndex]);

In the above example markup that equals "{{ tag | directive }}" would cause the partially match.


Solution

  • If we are expecting the markup to be plain text, you can just escape the whole variable when it is passed as a parameter in replaceText. I don't find this breaking anything you have and you won't modify anything else aside from the replaceText line.

    Sample:

    function escapeString() {
      var bodyObject = DocumentApp.getActiveDocument().getBody();
      
      markup = "{{ tag | directive }}";
      
      newString = "<mergeField>";
      // escape any non word character ($& = whole matched string)
      bodyObject.replaceText(markup.replace(/\W/g, "\\$&"), newString);
    }
    

    Before:

    sample

    After:

    after

    Reference: