0

I am trying to do a case insensitive find&replace in Google Docs using their Apps Api. I can't find a function that allows me to set this option (like in Slides or the User Interface) so will have to use body.replaceText() . Additionally I want use a variable to set the find string, but can't even get it to work with an explicitly given value.

I have tried different versions without success:
var findValue="foo"; var replaceValue="bar"

1) var regex = new RegExp('\\bfindValue\\b','gi');
   body.replaceText(regex,replaceValue);

2) var regex="/(\\b)"+findValue+"(\\b)/gi";
   body.replaceText(regex,replaceValue);

3) body.replaceText("/(\\b)"+findValue+"(\\b)/gi",replaceValue);

4) body.replaceText(/foo/gi,"bar");

Not even nr 4) finds Foo or foo in the text. Any suggestions?

  • You may refer with this [thread](https://stackoverflow.com/questions/30968419/replacetext-regex-not-followed-by). Be noted that the [`replaceText()`](https://developers.google.com/apps-script/reference/document/body#replaceText(String,String)) method doesn't support reverse-lookaheads or any other capture group. These restrictions apply only to the DocumentApp service. So it should be possible to manipulate your document at a lower level (extracting text from paragraph etc) but it could rapidly become quite cumbersome. – abielita Nov 25 '17 at 18:08

1 Answers1

3

On Google+ I got an answer that works: do not use the regex /foo/gi but instead

 var foo;
 var bar;
 var regex="(?i)\\b"+foo+"\\b";
 body.replaceText(regex,bar); 

this will replace the string in variable foo with the string in variable bar. Considered are only whole words (\b) and the search is case insensitive (?i). The regex is passed as a string which makes it necessary to add the extra '\'.