I would like to replace certain texts in a google document whenever it is opened. I have checked for a way to do this and all the solutions I found require either python or java, I am not familiar with these languages.
Is there a way to do this with Google Apps Script without external languages like python or java?
I believe your goal is as follows.
In this case, how about the following sample script by using the OnOpen simple trigger and replaceText
?
Please copy and paste the following script to the script editor of Google Document and save the script. By this, when Google Document is reopened, onOpen
is automatically run by the simple trigger.
In this sample, the sample value of replaceObj
is used. Please modify this for your actual situation. In this case, sample1
is replaced with sampleA
.
function onOpen(e) {
// Please set the replacement texts.
const replaceObj = [
{"from": "sample1", "to": "sampleA"},
{"from": "sample2", "to": "sampleB"},
];
const body = e.source.getBody();
replaceObj.forEach(({from, to}) => body.replaceText(from, to));
}
In this sample script, the event object is used. If you want to directly run the script with the script editor, please modify it as follows.
From
const body = e.source.getBody();
To
const body = DocumentApp.getActiveDocument().getBody();
From your following reply,
Yes, this is what I want to do, but I want the text replaced every time the document is opened. For example, if a particular text was "Apple" the first time the document was opened, the second time, it should be "Orange" and the third time, it should be "Cherry".
In this case, how about the following sample script?
function onOpen(e) {
// Please set the replace texts.
const replaceAr = ["Apple", "Orange", "Cherry"];
const len = replaceAr.length;
const body = e.source.getBody();
for (let i = 0; i < len; i++) {
const f = body.findText(replaceAr[i]);
if (f) {
body.replaceText(replaceAr[i], replaceAr[i < len - 1 ? i + 1 : 0]);
break;
}
}
}