1
votes

I'm using replaceText() for a project and I want to be able to match and replace strings that pan across multiple lines in Google Docs. Now in the 'replace' part of replaceText(), I'm able to use \n to insert line breaks in the new text, but for some reason I cannot use \n to match existing line breaks.

Say I have a string like this in Google Docs:

Line one

Line two

And I want to replace it with text "Just one line". I've tried doing the following and it hasn't worked.

doc.replaceText("Line one\n*Line two", "Just one line");
doc.replaceText("Line one\n\nLine two", "Just one line");
doc.replaceText("Line one\n+Line two", "Just one line");

Which leads me to believe that replaceText can't look for line breaks via \n. I was surprised, as it doesn't have any problems with using . or .* to look for random characters.

What would be a good solution for this? Another application for this that I need is deleting excess line breaks (so if there are three line breaks anywhere in a Doc, to delete them/turn them into one line break).

Keep in mind I'm very new to Javascript and only ever use it for Google Apps Script stuff on Google Docs. Please try to explain any solution in somewhat baby steps. Thanks in advance!

1
Does your document contain only text? - mikep
Yes, just text I think. It contains some links here and there, but most of them are just plain text, not even hyperlinked or whatever. Some colors and formatting are different in the text though, that's about it. - McHeisenbuhglah
See my answer below. Will that do? - mikep

1 Answers

0
votes

If your document contains only text (you will lose images etc),

var text = DocumentApp.getActiveDocument().getBody().getText();
var newText = text.replace(/\n/g,'');
doc.getBody().clear().appendParagraph(newText);