Search code examples
google-apps-scriptgoogle-slides-api

Delete slides that contain a specific text string


I'm working on an automated slide setup and depending on some opt-out variables I need to remove some of the slides if they are not desired in the final output. To solve this I have created a script that adds a simple text string {{remove-this-slide}} to the slides that need to be deleted.

However, when trying to get a script to delete the slides containing that string it keeps deleting my entire presentation...

This is what I have:

function deleteFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
  for (i = 0; i < currentPresentationSlide.length; i++) {
    if (currentPresentationSlide[i].getPageElements().indexOf('{{remove-this-slide}}') > -1); {
    currentPresentationSlide[i].remove();
  }
 }
}

Can anyone figure out what's going wrong here?


Solution

  • How about this modification?

    Modification points :

    • The reason that the entire slides are deleted is ; after if (currentPresentationSlide[i].getPageElements().indexOf('{{remove-this-slide}}') > -1);. By this ;, if doesn't work and currentPresentationSlide[i].remove(); is always run.
    • The text data cannot be retrieved from currentPresentationSlide[i].getPageElements(). When you want to search the text from the text box, please use currentPresentationSlide[i].getShapes().
      • From your question, I was not sure where you want to search the text from. So I supposed that you want to search the text from shapes. The shape includes the text box.

    Modified script :

    function deleteFunction() {
      var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
      for (i = 0; i < currentPresentationSlide.length; i++) {
        var shapes = currentPresentationSlide[i].getShapes();
        for (j = 0; j < shapes.length; j++) {
          if (shapes[j].getText().asString().indexOf('{{remove-this-slide}}') > -1) {
            currentPresentationSlide[i].remove();
          }
        }
      }
    }
    

    Reference :

    If I misunderstand your question, I'm sorry.