Reputation: 569
Trying to replace two or more new lines for one. Doc has images.
First i try to do line this:
var body = DocumentApp.getActiveDocument().getBody();
body.replaceText("\\n{2,}", '\n');
But Apps Script method replaceText does not accept escape characters.
Then I tried this:
var body = DocumentApp.getActiveDocument().getBody();
var bodyText = body.getText();
bodyText = bodyText.replace(/\n{2,}/, "\n");
body.setText(bodyText);
It works, but all images was miss.
How can i replace newlines with save Doc images?
Upvotes: 0
Views: 3860
Reputation: 50383
In Google docs, paragraphs are separated by \n
(newlines). A paragraph cannot contain a new line. Any new line character inside a paragraph is converted to \r
. The replaceText
documentation states:
The provided regular expression pattern is independently matched against each text block contained in the current element.
So, \n
cannot be used, because a text block(part of paragraph) cannot contain \n
.
One way to consider subsequent new lines is to consider them as empty paragraphs:
On that note, We can remove those empty paragraphs:
function removeEmptyParagraphs() {
DocumentApp.getActiveDocument()
.getBody()
.getParagraphs()
.forEach(para => {
const numChild = para.getNumChildren();
const txt = para.getText();
if (numChild === 0 && txt === '') para.removeFromParent();
});
}
Upvotes: 3