2

Replacing a paragraph break with something else in a Google Doc can be done via the "Find and Replace..." dialog box, using \n as a search pattern, with regular expressions enabled.

The same pattern, however, does not work in a Google Apps Script:

body = DocumentApp.getActiveDocument().getBody();
// note that escaping the backslash is required
body.replaceText("\\n", "EOL"); //matches nothing

even though:

body.replaceText("\\v", "EOL"); //matches "soft returns"
body.replaceText("\\s", "EOL"); //matches whitespace

The official reference is very terse, other than warning of the need to escape the backslashes.

It is obviously possible to solve the problem programmatically (see for example my own answer here), but does anyone know how to write a regular expression pattern that can be used as an argument in replaceText() and that matches a paragraph break?

Giuseppe
  • 5,188
  • 4
  • 40
  • 37
  • Possibly related: https://stackoverflow.com/questions/37771381/eliminate-newlines-in-google-app-script-using-regex https://stackoverflow.com/questions/40556574/google-apps-script-getbody-from-gmail-regex-n Are you getting any actual errors? Or simply, nothing is replaced? Please detail the escaping patterns you have tried – tehhowch Apr 27 '18 at 17:44
  • Does a simple "Find" (as in Find and Replace menu using regex option) for `\n` mark the correct positions? – TheMaster Apr 27 '18 at 17:54
  • @I'-'I yes, a simple Find-and-Replace with RegEx enabled WILL match `\n`. Which makes the script's apparent limitation even more frustrating – Giuseppe Apr 27 '18 at 20:30
  • @tehhowch, nothing is *matched*. Just for the heck of it, I have tried patterns containing from 1 all the way to 4 backslashes, as in `"\\\\n"` – Giuseppe Apr 28 '18 at 07:31
  • @bro, I have changed the title and rephrased much of the question, hope it's better now. – Giuseppe Apr 29 '18 at 15:27

0 Answers0