Search code examples
google-apps-scriptgoogle-appsgoogle-slides-apigoogle-slides

Is it possible to update/replace text in a specific slide?


Is it possible to update/replace text content in a specific slide?

Example - Assuming we have 5 slides in all and we have {product_name} in slide no 2,3,4. But we need to update/replace text {product_name} in slide no 3 only & not for slide no 2,4.

ReplaceAllText is possible but it will replace for all the slides wherever it finds {PRODUCT_NAME}, but we need to update the text for a specific slide only assuming slide no 3 only. I have explored a lot but could not find a way to achieve the same.

Snippet for ReplaceAllText (Works for all the slides replace, but we need the same for a specific slide & not for all): -

   requests = [{
      replaceAllText: {
        containsText: {
          text: '{{PRODUCT_NAME}}',
          matchCase: true
        },
        replaceText: PRODUCT_NAME
      }
    }

Thanks!


Solution

  • I believe your goal as follows.

    • You want to replace the text of {{PRODUCT_NAME}} in the 3rd slide in a Google Slides.
    • You want to achieve this using the batchRequest of Slides API with Google Apps Script.

    In this case, I thought that the property of pageObjectIds can be used.

    Modified script:

    function myFunction() {
      const PRODUCT_NAME = "sample value"; // Please set your actual value.
      const s = SlidesApp.getActivePresentation(); // or SlidesApp.openById("id")
      const pageElementId = s.getSlides()[2].getObjectId(); // pageElementId of 3rd page.
      console.log(pageElementId)
      const resource = {
        requests: [{
          replaceAllText: {
            pageObjectIds: [pageElementId],
            replaceText: PRODUCT_NAME,
            containsText: { matchCase: true, text: "{{PRODUCT_NAME}}" }
          }
        }]
      };
      Slides.Presentations.batchUpdate(resource, s.getId());
    }
    
    • const pageElementId = s.getSlides()[2].getObjectId(); returns the page element ID of 3rd page. This is used at pageObjectIds: [pageElementId].

    References: