I'm having trouble, replacing multi-lines text in a Google Doc, using App Script.
I've took the time to search and test similar questions I've learn a lot but I can't go through.
I have several blocs of text like below in my google Doc. I'm using tag labels to find what text bloc needs to be replaced. I replace the text block from "||TAG_LABEL" to "||"
||TAG_LABEL
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.||
From what I've learned I have to pass a string to replaceText.
I've checked the console and textToReplace is a string but the text is not replaced
function regexTestFunction(){
const document = DocumentApp.getActiveDocument();
const documentBody = document.getBody();
const keyWord = "TAG_LABEL";
const textToReplace = "\\|{2} (.*?)" keyWord "[\\s\\S]*?\\|{2}";
const deleteText = documentBody.replaceText(textToReplace,"");
}
Thank you for your help
CodePudding user response:
Set all lines to one line
function setTextToOneSentence() {
let d = DocumentApp.getActiveDocument();
let b = d.getBody();
b.setText("This is one sentence.")
}
CodePudding user response:
From your showing sample value as follows,
||TAG_LABEL
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.||
it seems that the value you want to replace has multiple paragraphs. In this case, it seems that replaceText
cannot be directly used. So, in this case, how about the following sample script?
Sample script:
In this sample script, Google Docs API is used. So, please enable Google Docs API at Advanced Google services.
function regexTestFunction() {
const document = DocumentApp.getActiveDocument();
const documentBody = document.getBody();
const keyWord = "TAG_LABEL";
const textToReplace = "\\|{2}.*?" keyWord "[\\s\\S]*?\\|{2}";
const r = new RegExp(textToReplace, "g");
const matches = documentBody.getText().match(r);
if (!matches || matches.length == 0) return;
const requests = matches.map(text => ({ replaceAllText: { containsText: { matchCase: false, text }, replaceText: "" } }));
Docs.Documents.batchUpdate({ requests }, document.getId());
}
When you run this script, your sample value is replaced with
""
which is empty.In this sample script, the following flow is used.
- Retrieve all texts from Document.
- Retrieve values using the regex of
textToReplace
from the texts. - Replace the matched texts using Google Docs API.
Note:
- I'm not sure about your actual Document. So when the above sample script was not useful, can you provide the sample Document? By this, I would like to confirm it.