Google Apps Script/Javascript search and replace with regex not working

wthman

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());
}
Henrique G. Abreu

As shown in the replaceText documentation, it expects a string on both parameters. The first one will automatically generate a RegExp for you. Therefore you can use a regular expression, but due to this syntax limitation, you can not pass RegExp flags to it (in your example the gim).

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).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related