Google Apps 脚本:将软换行符替换为硬换行符

Google Apps Script: Replace soft line break for hard line break

我有这个脚本可以使用 Google 电子表格中的信息替换 Google 文档中的文本。

输入

输入是 Google Sheet 中的一个单元格,有软换行符。

我想将那些软换行符转换为硬换行符。

目前的解决方案

我可以通过搜索 /\n/g 找到我写在 Google 电子表格上的软换行符。但是,当我尝试用 \r 替换 \n 时,我仍然遇到软换行符。

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

我能够验证它是软换行而不是硬换行,因为 Google 文档段落中的所有行都缩进了,就像软换行一样。

有人知道如何将软线换成硬线吗?

谢谢

来源:

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

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

根据您问题中的以下脚本以及示例输入和输出情况,

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

我认为当您的 Google 文档中包含换行符的值被替换为 {{Section Contents - Demo}} 时,缩进可能会在第 2 行之后更改。那么,在这种情况下,使用 Docs API 怎么样?使用文档API时,示例脚本如下

示例脚本:

在您使用此脚本之前,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);
}
  • 当此脚本为运行时,从Spreadsheet的SectionContentsDemo的命名范围中检索值,并在文档中将检索到的值替换为{{Section Contents - Demo}}。在这种情况下,缩进似乎遵循 {{Section Contents - Demo}}.

参考文献: