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

问题描述 投票:0回答:1

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

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

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

任何人都可以帮助我找到检测空行的方法吗?谢谢。

编辑:

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

javascript google-apps-script google-docs add-on google-apps-script-addon
1个回答
5
投票

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

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

  2. 转到文档菜单扩展>应用程序脚本

  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());
}

参考文献

  1. https://developers.google.com/apps-script/reference/document/text#replaceText(String,String)
  2. https://support.google.com/a/answer/1371415?hl=en
  3. https://stackoverflow.com/a/3012832/5285732
© www.soinside.com 2019 - 2024. All rights reserved.