替换 Google 文档中的新行 (\n)

Replacing new line (\n) in Google Docs

正在尝试将两个或多个新行替换为一个。文档有图片。

首先我尝试这样做:

var body = DocumentApp.getActiveDocument().getBody();
body.replaceText("\n{2,}", '\n');

但是 Apps 脚本方法 replaceText 不接受转义字符。

然后我试了这个:

var body = DocumentApp.getActiveDocument().getBody();
var bodyText = body.getText();
bodyText = bodyText.replace(/\n{2,}/, "\n");
body.setText(bodyText);

它有效,但所有图像都丢失了。

如何用保存的文档图像替换换行符?

问题:

在 Google 文档中,段落由 \n(换行符)分隔。段落不能包含新行。段落内的任何换行符都将转换为 \rreplaceText 文档指出:

The provided regular expression pattern is independently matched against each text block contained in the current element.

因此,不能使用\n,因为文本块(部分段落)不能包含\n

解决方案:

考虑后续新行的一种方法是将它们视为空段落:

  • 没有子项且
  • 的段落
  • 他的文字是空的

关于这一点,我们可以删除那些空段落:

片段:

function removeEmptyParagraphs() {
  DocumentApp.getActiveDocument()
    .getBody()
    .getParagraphs()
    .forEach(para => {
      const numChild = para.getNumChildren();
      const txt = para.getText();
      if (numChild === 0 && txt === '') para.removeFromParent();
    });
}

参考文献: