I'm trying to create a Google Docs script function that will replace all the instances of specific text including line breaks with other text that deletes the line break.
I have a long document that I'll be adding to regularly by coping and pasting from other text (I know, not ideal, but I don't have a way to export raw text) and then cleaning it up. In Google Docs I can do a Find and Replace for M\navatar\nM and replace it with M (With the "Match using regular expressions" checked) and then do another find and replace for J\navatar\nJ and replace with J to help with cleanup. I'd like to add these as functions in a script so I can do all the replacements at once.
I tried using the replaceText function, but it will not accept the \n expression for the line break and so it finds nothing.
This is just my guess for my understood your question. In your current issue of I tried using the replaceText function, but it will not accept the \n expression for the line break and so it finds nothing.
, I thought that the reason for this issue might be due to that replaceText
cannot be used for multiple paragraphs. If my understanding is correct, I thought that this sample script might be able to be used. Ref But, from your question, I thought that in this case, reflecting your goal in this sample script might be complicated a little. So, I would like to introduce a sample script for achieving your goal using the sample script as an answer as follows.
Please copy and paste the following script to the script editor of Google Document and save the script. Before you use this script, please enable Docs API at Advanced Google services.
function myFunction() {
// This is from your question.
const replaceTexts = [
{ "from": "M\navatar\nM", "to": "M" },
{ "from": "J\navatar\nJ", "to": "J" }
];
const doc = DocumentApp.getActiveDocument();
const requests = replaceTexts.map(({ from, to }) => ({ replaceAllText: { containsText: { matchCase: false, text: from }, replaceText: to } }));
Docs.Documents.batchUpdate({ requests }, doc.getId());
}
replaceAllText
of Google Docs API, it seems that the multipe paragraphs can be used.When this script is used, the following sample result is obtained. In this script, the format is kept even when the text is replaced.