Denis Ostrovsky
Denis Ostrovsky

Reputation: 569

Replacing new line (\n) in Google Docs

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

Answers (1)

TheMaster
TheMaster

Reputation: 50383

Issue:

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.

Solution:

One way to consider subsequent new lines is to consider them as empty paragraphs:

  • paragraphs with no children and
  • whose text is empty

On that note, We can remove those empty paragraphs:

Snippet:

function removeEmptyParagraphs() {
  DocumentApp.getActiveDocument()
    .getBody()
    .getParagraphs()
    .forEach(para => {
      const numChild = para.getNumChildren();
      const txt = para.getText();
      if (numChild === 0 && txt === '') para.removeFromParent();
    });
}

References:

Upvotes: 3

Related Questions