Hard Line Break in Docs App Script

25 views
Skip to first unread message

Anthony Moltisanti

unread,
Jun 11, 2024, 2:16:26 AM (13 days ago) Jun 11
to Google Apps Script Community
Hello, I'm new to the community, so please forgive any faux pas on my part.

I have a Google Doc which contains character dialogue for a script. For example...

Bob: Hello!

I'm trying to use App Script to quickly reformat a large number of lines in the same vein as above, i.e. <name>: <text>. I found a pretty simple function that locates any instance of ": " and replaces it with a newline:

function myFunction() {
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      body.replaceText(': ', '\n');
    }

This part works successfully. My initial example becomes...

Bob
Hello!

My problem is that \n appears to be a soft line break, as though I'd pressed Shift+Enter in the Doc. If I try to indent either "Bob" or "Hello!", it indents both of them rather than just the one I've selected. I've tried using \r, but I get the same issue.

Is there a code for a hard line break, equivalent to pressing Enter in the Doc, that doesn't tie the formatting of the two lines together?

Tanaike

unread,
Jun 11, 2024, 3:59:05 AM (13 days ago) Jun 11
to Google Apps Script Community
In your situation, is this thread on Stackoverflow useful? https://stackoverflow.com/q/78258654

Anthony Moltisanti

unread,
Jun 12, 2024, 2:33:02 AM (12 days ago) Jun 12
to Google Apps Script Community
It did! Thank you!

As suggested in the link, I added Google Docs API to my document and then slightly adjusted the suggested code. The following worked:

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const requests = [{ replaceAllText: { replaceText: "\n", containsText: { text: ": " } } }];
  Docs.Documents.batchUpdate({ requests }, doc.getId());
}

For some reason \n here works as a hard return. Not gonna question it, just happy it works. Thanks again!

Reply all
Reply to author
Forward
0 new messages