如何使用脚本编辑器(Google Docs Add-ons)删除Google文档中的空行? [英] How to remove empty lines in a google doc using the script editor (Google Docs add-ons)?

查看:39
本文介绍了如何使用脚本编辑器(Google Docs Add-ons)删除Google文档中的空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Google Docs加载项,其中一个功能是减少两个段落之间的空行数量。

因此,例如,如果我有两个段落,中间有5个空行,我希望该功能将空行的数量减少到1。

本质上,我需要一种方法来检测空行。我已经研究了API,并且认为我需要使用replaceText()方法来搜索正则表达式模式。然而,我已经尝试过了,但它不起作用(可能我使用了错误的模式,我不知道)。

有人能帮我找到检测空行的方法吗?谢谢。

编辑:

我刚刚发现Google Docs并不支持所有的正则表达式模式。链接如下:https://support.google.com/analytics/answer/1034324?hl=en。我不熟悉正则表达式。有没有人能提供在Google Docs中运行的替代方案。

推荐答案

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

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

  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:
", 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:
", 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

这篇关于如何使用脚本编辑器(Google Docs Add-ons)删除Google文档中的空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆