[英]How to remove empty lines in a google doc using the script editor (Google Docs add-ons)?
I am creating a Google Docs add-on, and one of the features I am trying to create is a feature that reduces the number of empty lines between two paragraphs.我正在创建一个 Google Docs 插件,我正在尝试创建的功能之一是减少两个段落之间的空行数量的功能。
So, for instance, if I have 2 paragraphs with 5 empty/blank lines between them, I want the feature to reduce the number of empty lines to 1.因此,例如,如果我有 2 个段落,它们之间有 5 个空行/空行,我希望该功能将空行数减少到 1。
Essentially, I need a way to detect an empty line.本质上,我需要一种检测空行的方法。 I've looked at the API , and think I need to use the replaceText() method which searches for a regex pattern.我查看了API ,并认为我需要使用搜索正则表达式模式的 replaceText() 方法。 However, I've tried it, and it didn't work (perhaps I'm using an incorrect patter, i dont know).但是,我已经尝试过了,但它没有用(也许我使用了不正确的模式,我不知道)。
Can anyone help me in finding a way to detect an empty line?谁能帮我找到一种检测空行的方法? Thanks.谢谢。
EDIT:编辑:
I just found out that Google Docs don't support all patterns of regex.我刚刚发现 Google Docs 并不支持所有的正则表达式模式。 Here is that link: https://support.google.com/analytics/answer/1034324?hl=en .这是该链接: https://support.google.com/analytics/answer/1034324?hl=en 。 I'm not familiar with regex.我不熟悉正则表达式。 Can anyone provide an alternative that works in Google Docs.任何人都可以提供适用于 Google Docs 的替代方案。
Written and tested the below function, here are the steps to make it work编写并测试了以下 function,以下是使其工作的步骤
Copy the text from here Lorem Ipsum Google Doc , to a new Google Doc将文本从Lorem Ipsum Google Doc复制到新的 Google Doc
Add the below snippet to your Tools > Script editor > project将以下代码段添加到您的工具 > 脚本编辑器 > 项目
Comments inline内联评论
// 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());
}
References
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.