如何使用脚本编辑器(Google Docs 插件)删除 google 文档中的空行?

lak*_*hk4 3 javascript add-on google-docs google-apps-script google-apps-script-addon

我正在创建一个 Google Docs 插件,我试图创建的功能之一是减少两个段落之间的空行数量。

因此,举例来说,如果我有 2 个段落,它们之间有 5 个空行/空白行,我希望该功能将空行数减少到 1。

本质上,我需要一种方法来检测空行。我查看了API,认为我需要使用 ReplaceText() 方法来搜索正则表达式模式。但是,我已经尝试过,但没有成功(也许我使用了错误的模式,我不知道)。

谁能帮我找到一种检测空行的方法?谢谢。

编辑:

我刚刚发现 Google 文档不支持所有正则表达式模式。这是该链接: https: //support.google.com/analytics/answer/1034324 ?hl =en。我对正则表达式不熟悉。任何人都可以提供适用于 Google Docs 的替代方案吗?

Mei*_*bay 5

编写并测试了以下功能,以下是使其工作的步骤

  1. 将文本从此处Lorem Ipsum Google Doc复制到新的 Google 文档

  2. 转到“文档”菜单“扩展”>“Apps 脚本”

  3. 复制并粘贴下面给出的脚本:

// Regular expressions with the following special characters are not supported, 
// as they can cause delays in processing your email: * (asterisk), + (plus sign)
// So RegEx is not applicable since you can't use "\s*", we need to find another solution

// A row/line is a Paragraph, weird right? So now you iterate through the rows
// Trim paragraph (row), if it's empty, then you can delete it.

function removeEmptyLines() {
  var doc = DocumentApp.getActiveDocument();
  Logger.log("Before:\n", doc.getBody().getText());  
  
  var paragraphs = doc.getBody().getParagraphs();
  // Iterating from the last paragraph to the first
  for (var i=paragraphs.length-1; i>=0; i--){
    var line = paragraphs[i];
    if ( ! line.getText().trim() ) {
      // Paragraph (line) is empty, remove it
      line.removeFromParent()
      Logger.log("Removed: ", i);
    }
  }
  Logger.log("After:\n", doc.getBody().getText());
}
Run Code Online (Sandbox Code Playgroud)

参考

  1. https://developers.google.com/apps-script/reference/document/text#replaceText(String,String)
  2. https://support.google.com/a/answer/1371415?hl=en
  3. /sf/answers/210898271/