wepli23
wepli23

Reputation: 87

How to use findText case insensitive?

I try to search for a string in Google Document. By default findText is case sensitive. How can I use it case insensitive.

The reference says "Searches the contents of the element for the specified text pattern using regular expressions."

That's what I tried:

function search(string) {
  var pattern = new RegExp(string, "gi");
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var rangeElement = body.findText(pattern);
  while (rangeElement) {
    var offset =rangeElement.getStartOffset();
    var text = rangeElement.getElement().asText().getText();
    html += text;
  } 
}

But it doesn't find anything. I also tried:

body.findText(pattern(string)); and body.findText(/string/\i);

Anything else I can try?

Upvotes: 2

Views: 1584

Answers (2)

TheMaster
TheMaster

Reputation: 50501

Issues:

  • Sending Regexp "object" instead of "string" type to findText()
  • Incorrect syntax for case insensitivity.

Solution:

  • Use proper re2 syntax
  • Send regex as string. This means special characters\s are double escaped \\s

    findText('(?i)Apple') //matches APPLE or AppLe 
    

To Read:

Upvotes: 6

As we can read in the official reference,

A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.

In addition, be attentive to use pattern argument of the findText(): it must be a string, not RegExp object.

Upvotes: 1

Related Questions