Search code examples
google-apps-scriptgoogle-docs

Remove line breaks using apps scripts in a Google Document


Trying to work out how to remove multiple line breaks from Google Documents (not spreadsheets).

I've tried this and many variations thereof:

function searchAndReplace() {
  var bodyElement = DocumentApp.getActiveDocument().getBody();
  bodyElement.replaceText("\r\r", '\r');
}

Any idea please? Noob to all of this...

Purpose is to replicate the search and replace in MS Word for ^p


Solution

  • Here is a rather "radical" method if your document has only paragraphs with text (images or other elements will be lost). See doc about element types here

    (comments in code)

    function removeNewLines(){
      var doc = DocumentApp.getActiveDocument();
      var text = doc.getBody().getText();// get a string
      var textMod=text.replace(/\n/g,'');// replace all \n with ''
      Logger.log(textMod);//optional check in logger
      doc.getBody().clear().appendParagraph(textMod);// empty the doc and apend new texr
      doc.saveAndClose();// save the result
    }