【问题标题】:How to remove empty lines in a google doc using the script editor (Google Docs add-ons)?如何使用脚本编辑器(谷歌文档插件)删除谷歌文档中的空行?
【发布时间】:2020-11-27 01:03:01
【问题描述】:

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

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

基本上,我需要一种方法来检测空行。我查看了API,并认为我需要使用搜索正则表达式模式的replaceText() 方法。但是,我试过了,但它没有用(也许我使用了不正确的模式,我不知道)。

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

编辑:

我刚刚发现 Google Docs 并不支持所有的正则表达式模式。这是该链接:https://support.google.com/analytics/answer/1034324?hl=en。我不熟悉正则表达式。谁能提供适用于 Google Docs 的替代方案。

【问题讨论】:

  • 在正则表达式中,^ 是行首,$ 是行尾,\s 是一个空格。将它们组合在一起 - 尝试使用 ^\s*$ 星号表示“任意数量的空格”
  • 这是有道理的。但由于某种原因,它仍然不起作用。
  • 我很感兴趣,解决它并回复一个解决方案

标签: javascript google-apps-script google-docs add-on google-apps-script-addon


【解决方案1】:

编写并测试了下面的函数,这里是使它工作的步骤

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

  2. 将下面的 sn-p 添加到您的工具 > 脚本编辑器 > 项目中

  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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多