Home > Mobile >  Would it be possible to create a script which would search and highlight multiple words within a Goo
Would it be possible to create a script which would search and highlight multiple words within a Goo

Time:02-11

So I would like to be able to have the ability to search up to 30 phrases within a Google doc. Currently I have to do this process manually with find and replace tool.

But could a script automate this process in someway where it would search for the words and highlight them within the doc for me to review.

CodePudding user response:

Issue:

If I understand you correctly, you want to highlight (by highlight, I assume you mean changing the background color) certain sentences if they are present in your document.

Solution:

  • For each sentence, use Body.findText(sentence) to find its first occurrence in the document.
  • Retrieve the start and end offset of the resulting RangeElement.
  • Check whether the corresponding element can be edited as text and obtain a text version of it (see editAsText()).
  • Change the background color using setBackgroundColor.

Code sample:

const sentences = ["First sentence", "Second"]; // Your sentences

function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}
  • Related