Skip to content

Instantly share code, notes, and snippets.

@erickoledadevrel
Last active February 20, 2020 13:32
Show Gist options
  • Save erickoledadevrel/bec0993dfada5f1aebfb to your computer and use it in GitHub Desktop.
Save erickoledadevrel/bec0993dfada5f1aebfb to your computer and use it in GitHub Desktop.
Remove multiple line breaks in a Googe Document using Apps Script
function removeMultipleLineBreaks(element) {
if (!element) {
element = DocumentApp.getActiveDocument().getBody();
}
var parent = element.getParent();
// Remove empty paragraphs
if (element.getType() == DocumentApp.ElementType.PARAGRAPH
&& element.asParagraph().getText().replace(/\s/g, '') == '') {
if (!(parent.getType() == DocumentApp.ElementType.BODY_SECTION
&& parent.getChildIndex(element) == parent.getNumChildren() - 1)) {
element.removeFromParent();
}
// Remove duplicate newlines in text
} else if (element.getType() == DocumentApp.ElementType.TEXT) {
var text = element.asText();
var content = text.getText();
var matches;
// Remove duplicate carriage returns within text.
if (matches = content.match(/\r\s*\r/g)) {
for (var i = matches.length - 1; i >= 0; i--) {
var match = matches[i];
var startIndex = content.lastIndexOf(match);
var endIndexInclusive = startIndex + match.length - 1;
text.deleteText(startIndex + 1, endIndexInclusive);
}
}
// Grab the text again.
content = text.getText();
// Remove carriage returns at the end of the text.
if (matches = content.match(/\r\s*$/)) {
var match = matches[0];
text.deleteText(content.length - match.length, content.length - 1);
}
// Remove carriage returns at the start of the text.
if (matches = content.match(/^\s*\r/)) {
var match = matches[0];
text.deleteText(0, match.length - 1);
}
// Recursively look in child elements
} else if (element.getNumChildren) {
for (var i = element.getNumChildren() - 1; i >= 0; i--) {
var child = element.getChild(i);
removeMultipleLineBreaks(child);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment