I know there are many similar questions and answers out there but I have had no luck.
I simply want to run a regex on a Google Doc and have it replace what it finds with Uppercase. I have a working regular expression, and a simple string replace works, but I can't get a regex of any kind to work. What am I doing wrong?
function searchAndReplace() {
var bodyElement = DocumentApp.getActiveDocument().getBody();
var regExp = new RegExp(/[\n][\n]([^\n]+)[\n][^\n|\s]/gim);
bodyElement.replaceText(regExp, '$1'.toUpperCase());
}
As shown in the replaceText documentation, it expects a
string
on both parameters. The first one will automatically generate aRegExp
for you. Therefore you can use a regular expression, but due to this syntax limitation, you can not passRegExp
flags to it (in your example thegim
).Also, since the second parameter also only accepts a string, you can not inform a function, which is what you'd need to make a proper
toUpperCase
(which is wrong in your example even if using javascript built-in string.replace function).And from tests I just made, replacement string patterns using "$&" or "$#" don't work either.
So, to achieve what you're looking for you'll have to implement this search-and-replace yourself (possibly using findText to help on the "search" part).