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

RegEx Google Apps Script with replaceAllText


I've tried to replace some text in Google Slides with replaceAllText, it works fine if I provide the string, however I can't find the solution for regex.

What I want to change is:

N = 500

Regex variations I tried with replaceAllText:

/N [=, 0-9]*/
"N [=, 0-9]*"
"N = [0-9]*"
"N = \d*"
/N = \d*/

but nothing worked.

How can I use replaceAllText with regex?


Solution

  • Issue:

    replaceAllText doesn't support regular expressions, but exact substring matches.

    Solution:

    You should be using find(pattern) instead:

    find(pattern): Returns all the ranges matching the search pattern in the current text range. The search is case sensitive.

    Code sample:

    For example, if you wanted to find and replace all regex matches in the presentation, you could do the following:

    // Copyright 2020 Google LLC.
    // SPDX-License-Identifier: Apache-2.0
    
    function findAndReplace() {
      var pres = SlidesApp.getActivePresentation();
      var slides = pres.getSlides();
      const pattern = "N = \\d*";
      slides.forEach(slide => { // Iterate through every slide in the presentation
        slide.getShapes().forEach(shape => { // Iterate through every shape in the slide
          const textRange = shape.getText(); // Get shape text
          const matches = textRange.find(pattern); // Find matches
          matches.forEach(match => match.setText("REPLACED TEXT")); // Replace text
        });               
      });
    }
    

    Note:

    • The expression in the code sample above (N = \\d*) has two backslashes, because, as the docs say, any backslashes in the pattern should be escaped. A possible alternative could be N = [0-9]*.