Search code examples
javascriptgoogle-apps-scriptgoogle-drive-apigoogle-docsgoogle-apps

Paint certain words in google docs - Google Apps Script


I have this code below:

        var textToHighlight = 'Normal';
        var highLightStyle = {};
        highLightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FFC0CB';
        var paras = doc.getParagraphs();
        var textLocation = {};

        for (i=0; i<paras.lenght; i++) {
          textLocation = paras[i].findText(textToHighlight);
          if (textLocation != null && textLocation.getStartOffset() != -1) {
            textLocation.getElement().setAttributes(textLocation.getStartOffset(), textLocation.getEndOffsetInclusive(), highLightStyle);
          }
        }

With it, I want to color all the words 'normal' that appear in my document, but when I run the code, nothing happens and it doesn't accuse any error, it compiles normally.

I tried this another code:

        let pinkColor = "#FFC0CB"
        let pinkElements = body.findText("Normal")
        let elem = pinkElements.getElement().asText();
        let t = elem.getText();
        elem.setForegroundColor(t.indexOf('Normal'), t.indexOf('High')+3, pinkColor)

But with the code above it paints only the first word 'Normal' that it finds, the rest remains neutral.

Does anyone know what may be happening to both codes?


Solution

  • Does anyone know what may be happening to both codes?

    Code 1:

    You made a typo, lenght should be length.

    Code 2:

    See my answer below.

    Explanation:

    You need to iterate over all elements with the particular keyword.

    To achieve that you need to follow these steps:

    1. get the first found element:

      pinkElement = body.findText(searchWord);

    2. check if an element with searchWord exists

    3. do some code for this element

    4. assign a new element which is the next one you found before:

      pinkElement = body.findText(searchWord, pinkElement);

    5. repeat steps 1-4 until there is no other element:

      while (pinkElement != null)

    Solution:

    function myFunction() {
       let doc = DocumentApp.getActiveDocument();
       let body = doc.getBody();
       let pinkColor = "#FFC0CB";
       let searchWord = "Normal";
       let pinkElement = body.findText(searchWord);
       while (pinkElement != null) {
         let elem = pinkElement.getElement().asText();
         let t = elem.getText();
         elem.setForegroundColor(t.indexOf(searchWord), t.indexOf('High')+3, pinkColor);
         pinkElement = body.findText(searchWord, pinkElement);
       }
    }