Home > Software design >  Continuously replace text in google doc with google doc api
Continuously replace text in google doc with google doc api

Time:10-29

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?

CodePudding user response:

I believe your goal is as follows.

  • When Google Document is opened, you want to replace the texts in the Google Document.
  • You want to use Google Apps Script.

In this case, how about the following sample script by using the OnOpen simple trigger and replaceText?

Sample script:

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();
      

References:

Added:

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?

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;
    }
  }
}
  • When Google Document is opened, when this script is run, when "Apple" is found in the Document, it is replaced with "Orange". And, when Google Document is opened, again, when this script is run, when "Orange" is found in the Document, it is replaced with "Cherry". And, when Google Document is opened, again, when this script is run, when "Cherry" is found in the Document, it is replaced with "Apple".
  • Related