[英]How to remove empty lines in a google doc using the script editor (Google Docs add-ons)?
我正在创建一个 Google Docs 插件,我正在尝试创建的功能之一是减少两个段落之间的空行数量的功能。
因此,例如,如果我有 2 个段落,它们之间有 5 个空行/空行,我希望该功能将空行数减少到 1。
本质上,我需要一种检测空行的方法。 我查看了API ,并认为我需要使用搜索正则表达式模式的 replaceText() 方法。 但是,我已经尝试过了,但它没有用(也许我使用了不正确的模式,我不知道)。
谁能帮我找到一种检测空行的方法? 谢谢。
编辑:
我刚刚发现 Google Docs 并不支持所有的正则表达式模式。 这是该链接: https://support.google.com/analytics/answer/1034324?hl=en 。 我不熟悉正则表达式。 任何人都可以提供适用于 Google Docs 的替代方案。
编写并测试了以下 function,以下是使其工作的步骤
将文本从Lorem Ipsum Google Doc复制到新的 Google Doc
将以下代码段添加到您的工具 > 脚本编辑器 > 项目
内联评论
// 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());
}
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.