google-apps-scriptgoogle-slides

Why does filtering an array come back with an error?


I want to filter an array of text for numbers between 0 and 3.75 on google slides but it always comes back with an error and I don't know if the m variable isn't an array or if it's apps script being weird.

var text = shape.getText();
  let m = String(text).match(/[0-9.]{1,}/g);

  let r1 = m.filter(e => e >= 0 && e <= 3.75);

the error being

TypeError: Cannot read properties of null (reading 'filter')

text gets all the text inside the google slides m gets all numbers between 0-9 r1 should filter all objects in m between 0 and 3.75, but here it breaks. is it because the match doesn't work with google slides?


Solution

  • Issue:

    TypeError: Cannot read properties of null (reading 'filter')

    m.filter(e => e >= 0 && e <= 3.75);
    

    This means that the variable m is null. m is the result ofString.match.

      let m = String(text).match(/[0-9.]{1,}/g);
    

    The result of String.match is null only when the regex doesn't match the text.

    Return value: An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

    Why doesn't text match the regex?

    1. The shape doesn't actually contain numbers.

    2. If the shape actually contains numbers(Which is more probable), the return of Shape.getText is not String, but TextRange

       var text = shape.getText();
      

      text is of type TextRange class. String(TextRange) doesn't get the raw data of the string in the shape, but a literal string TextRange.

    Solution:

    Call TextRange.asString to get the raw data inside it as String.

    Snippet:

      let m = text.asString().match(/[0-9.]{1,}/g);