Search code examples
google-apps-scriptgoogle-docsre2

Can findText return multiple RangeElements?


I want to be able to find and return all matching text in a Doc. findText current does a good job of returning the first occurrence of the searchPattern as a RangeElement. The problem is that regardless of the searchPattern which can be an RE2 regex, and regex can request for global match meaning all occurrence of the searchPattern in the active Doc, but findText only return a single result.

For example:

let text = "any";
const body = DocumentApp.getActiveDocument().getBody();
const searchResult = body.findText(`${text}*`);

What am I missing or getting wrong?

Are there any workarounds?


Solution

  • There is no direct way. The script should skip over all the found range elements and the start the search after the last found range element, using .findText(re2: String, from: rangeElement)

    const allResults = [];
    let thisResult = body.findText(`${text}*`);
    while (thisResult !== null) {
      allResults.push(thisResult);
      thisResult = body.findText(`${text}*`, thisResult);
    }