Search code examples
regexgoogle-apps-scriptre2

Apps Script Regex - Case Insensitive


I am writing an apps script for Google Docs. I am using findText() to locate an instance of a specified string of characters.

By default, it is case sensitive and I need to remove that, but I can't figure out how to add the /i to the re2 regex so that it works in apps script engine.

In my example, I am trying for find all instances of micssys (e.g. micssys, Micssys, MICSSYS, etc).

Right now I have:

var text = "micssys";
var bodyElement = DocumentApp.getActiveDocument().getBody();
var searchResult = bodyElement.findText(text);

I have tried:

var searchResult = bodyElement.findText("/"+text+"/i");

var searchResult = bodyElement.findText(text+"/i");

var searchResult = bodyElement.findText(text+"(i)");

None of these work. What am I missing


Solution

  • If I recall, I believe you can create a new regexp object and use exec here.

    var re = new RegExp('\\bmicssys\\b','gi');
    
    var match;
    var bodyElement = DocumentApp.getActiveDocument().getBody();
    while (match = re.exec(bodyElement)) {
       // match[0] will return the found results
    }
    

    Note: You may have to use getText() to retrieve the contents of the element as a text string and then match against.