Reputation: 53
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.
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.
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. 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. Here is that link: 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.
Upvotes: 3
Views: 4020
Reputation: 3286
Written and tested the below function, here are the steps to make it work
Copy the text from here Lorem Ipsum Google Doc, to a new Google Doc
Go to the Docs menu Extensions > Apps Script
Copy and paste the script given below:
// 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());
}
Upvotes: 5