How can I use Google Apps Script to substitute multi-line text in Google Docs with a specific string?

I am facing challenges in substituting multi-line text sections within a Google Document through Apps Script. Despite researching and trying out various solutions, I’m still stuck. I have multiple sections of text in my document and I identify these sections using specific tag labels. For instance, I want to replace the block that appears between “||TAG_LABEL” and “||”. Here’s an example block:

||TAG_LABEL
Sample text example goes here.
More details to follow.
||


My understanding is that I need to provide a string for the replaceText method. I have verified that the value for textToReplace is a string, yet it isn’t functioning as expected and the text remains unchanged.
Here’s the code I’ve been working with:
function replaceTextInDocument() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); const label = “TAG_LABEL”; const pattern = “\|{2} (.?)" + label + "[\s\S]?\|{2}”; body.replaceText(pattern, “”); }

I appreciate any assistance you can provide!

The issue might be related to the regular expression pattern you are using. In Apps Script, unlike JavaScript running in a browser, some regex functionalities like multiline matching are not supported directly. However, you can try tweaking your approach by simplifying your regex or use a workaround.

You can retrieve the whole text of the document as a string, search for the text using a simple loop and replace the text. Once you’ve manipulated the string as needed, update the document content. This approach, while not as elegant as a regex, can be quite effective for multiline replacements.