Home > OS >  Google Apps Script: Replace soft line break for hard line break
Google Apps Script: Replace soft line break for hard line break

Time:11-22

I have this script that replaces text in a Google Doc using info from a Google Spreadsheet.

Input

The input is a cell inside a Google Sheet that has soft line breaks. enter image description here

I would like to convert those soft line breaks into hard line breaks.

Solution so far

I'm able to find the soft line break I write on the Google Spreadsheet by searching for /\n/g. However when I try to replace \n with \r I'm still getting soft line breaks.

demo_content = ss.getRangeByName("SectionContentsDemo").getValue().toString().replace(/\n/g,'\r\n'),
template_doc_body.replaceText("{{Section Contents - Demo}}", demo_content);

I'm able to validate that it's a soft line break instead of a hard one because all the lines in the Google Doc paragraph are indented, as a soft line break would behave.

enter image description here

Anyone has an idea on how to replace the soft line breaks into hard ones?

Thanks

Sources:

https://docs.google.com/spreadsheets/d/1VAU0-COifUd2j1PA5_td3tuDnBSqcnOo_4-cMqiAFUI

https://docs.google.com/document/d/1dQaDipbs3BkMYcHx_1s6qFjyltmLtbTrzzlmVX3Cl1o/

CodePudding user response:

From your following script in your question and your sample input and output situations,

demo_content = ss.getRangeByName("SectionContentsDemo").getValue().toString().replace(/\n/g,'\r\n'),
template_doc_body.replaceText("{{Section Contents - Demo}}", demo_content);

I thought that when the value including the line break is replaced with {{Section Contents - Demo}} in your Google Document, the indent might be changed after 2nd line. So, in this case, how about using Docs API? When the Docs API is used, a sample script is as follows.

Sample script:

Before you use this script, please enable Docs API at Advanced Google services.

function myFunction() {
  var template_id = '###'; // Please set your template Google Document ID.

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var value = ss.getRangeByName("SectionContentsDemo").getValue();
  var documentId = DriveApp.getFileById(template_id).makeCopy().getId();
  Docs.Documents.batchUpdate({
    requests: [
      {
        replaceAllText: {
          replaceText: value,
          containsText: { matchCase: true, text: "{{Section Contents - Demo}}" }
        }
      }]
  }, documentId);
}
  • When this script is run, the value is retrieved from the named range of SectionContentsDemo of Spreadsheet, and the retrieved value is replaced with {{Section Contents - Demo}} in the document. In this case, it seems that the indent is followed to {{Section Contents - Demo}}.

References:

  • Related