google-apps-scriptgoogle-slides

Format specific words in a Google Slide using App Script


I'm trying to extract a word from a Google Slide and replace its formatting. I was able to do it with this custom function, but it works only with the text that is selected :

function formatSelectedText() {
  var selection = SlidesApp.getActivePresentation().getSelection();
  var textRange = selection.getTextRange();
  if (textRange) {
    var textStyle = textRange.getTextStyle();
    textStyle.setFontSize(11).setFontFamily('Arial');
  } else {
    Logger.log('No text selected or invalid selection.');
  }
}

But I would like the function to find words and replace formatting without having to select anything manually on the Google slide.


Solution

  • I believe your goal is as follows.

    In this case, it is required to search all texts in all slides in a Google Slide. In my answer, I check the shapes, the tables, and the groups including the shapes and the tables. But, unfortunately, I do not know your Google Slides. So, this is just my guess. The sample script is as follows.

    Sample script:

    Please set your search text.

    function myFunction() {
      var searchText = "sample"; // Please set your search text.
    
      var setStyle_ = text => {
        const search = text.find(searchText);
        if (search.length == 0) return;
        search.forEach(se => se.getTextStyle().setFontSize(11).setFontFamily('Arial'));
      }
      var checkTable_ = table => {
        for (let r = 0; r < table.getNumRows(); r++) {
          const row = table.getRow(r);
          for (let c = 0; c < row.getNumCells(); c++) {
            setStyle_(row.getCell(c).getText());
          }
        }
      }
      var slides = SlidesApp.getActivePresentation().getSlides();
      slides.forEach(slide => {
        slide.getShapes().forEach(shape => setStyle_(shape.getText()));
        slide.getTables().forEach(checkTable_);
        slide.getGroups().forEach(g => {
          g.getChildren().forEach(c => {
            const type = c.getPageElementType();
            if (type == SlidesApp.PageElementType.SHAPE) {
              setStyle_(c.asShape().getText());
            } else if (type == SlidesApp.PageElementType.TABLE) {
              checkTable_(c.asTable());
            }
          });
        });
      });
    }
    

    References: