3

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());
}
wthman
  • 97
  • 1
  • 2
  • 7

1 Answers1

0

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

Henrique G. Abreu
  • 17,406
  • 3
  • 56
  • 65
  • Thanks! Now I see why it doesn't work. Bummer tho! :( – wthman Jul 19 '14 at 03:42
  • 1
    You're welcome. And since you're new to StackOverflow, please remember to accept an answer when you feel you got a good one. It's a check mark under the voting arrows (another nice SO feature). – Henrique G. Abreu Jul 19 '14 at 12:21
  • 1
    Thanks. Technically you answered my question why my function doesn't work. But I still don't have a solution to finding and replacing the strings I'm interested in in google apps script. Should I open another question for that? – wthman Jul 19 '14 at 14:47
  • 1
    Yes, I answered you (since the bottom line question was "What am I doing wrong?"). And I even explained you how to solve it (by coding it yourself, using `findText` and then built-in string `replace`). There's no easy way. Just to clarify, asking for ready programs/functions is not a programming doubt, which is StackOverflow's scope. If you attempt to code it yourself and get stuck, then you should open a new question. – Henrique G. Abreu Jul 19 '14 at 20:21