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

search slide and get page element text


My script searches one specific slide in a presentation. Then it gets the text from the first page element. This page element is a shape with only one word. After this, when I put strings before and after this page element text, there is a break in the text.

function readShapeText() {
   var presentation = SlidesApp.getActivePresentation();
   var slides = presentation.getSlides();
   
   for (i = 0; i < slides.length; i++) {
    
       if(slides[i].getObjectId() == 'mySlideId'){
 
         var pageElement = slides[i].getPageElements()[0].asShape().getText().asString();
          
       }
   }
    
   var myModifiedElement = "My_" + pageElement + "_is_cool";
}

The output is with a break, but I need in one line:

My_TestElement

_is_cool

How can I eliminate or suppress the break? And is there a better way to find a specific slide without using "for loop" f.e. like presentation.openSlideById(xxxxxx)?


Solution

  • How about these answers?

    Q1: How can I eliminate or suppress the break?

    It seems that the end of texts is always given \n. This can be also seen from values retrieved by Slides.Presentations.get(). So if you want to retrieve the values without \n, you can do it using replace("\n", "").

    Q2: Is there a better way to find a specific slide without using "for loop" f.e. like presentation.openSlideById(xxxxxx)?

    How about the following sample script? It retrieved the specific slide using filter(), because the key of objectId is included in the array. And replace("\n", "") was also used.

    function readShapeText() {
      var mySlideId = "mySlideId"; // Please input this.
      var presentation = SlidesApp.getActivePresentation();
      var slides = presentation.getSlides();
      var slide = slides.filter(function(e){return e.getObjectId() == mySlideId})[0];
      var pageElement = slide.getPageElements()[0].asShape().getText().asString().replace("\n", "");
      var myModifiedElement = "My_" + pageElement + "_is_cool";
      Logger.log(myModifiedElement)
    }
    

    If I misunderstand your question, I'm sorry.