How to use replaceText function with special characters (ñ, ?, ()...)

320 views
Skip to first unread message

Xavier Pacheco Romero

unread,
Sep 14, 2022, 5:05:18 PM9/14/22
to Google Apps Script Community
Greetings to all, I wanted to know your help with the use of the replaceText function, the issue is that I want to search for a text in the body of a document and replace it with another text.

The document template has the following "fields" to replace:

Nombres: {{Nombres}}

Apellidos: {{Apellidos}}

Sexo: {{Sexo}}

Edad: {{Edad (años)}}


So the idea is to replace every text that starts and ends with the double braces (Example: {{Names}} ). To achieve this goal I use the replaceText function and it works very well for the most part except for  Edad: {{Edad (años)}}  , and this is because this "field" contains special characters such as the letter ñ in its name and the parentheses () (I changed the field from  {{Edad (años)}}   to {{Edad anios}} and it works perfectly), it is also worth mentioning that other fields have the question marks ¿?.

Incidentally, the name of this field {{Edad (años)}}  , is the result of a Google Forms form, so I can NOT change the name of the "field" Age.

The code I use to replace is the following:

let NewFile = DocumentApp.openById(IDDocument);
NewFile.getBody().replaceText(" {{Edad (años)}}  ", "42 years");

I thank you in advance for your prompt help.
Greetings.

Tanaike

unread,
Sep 15, 2022, 1:20:46 AM9/15/22
to Google Apps Script Community
I thought that in the case of "NewFile.getBody().replaceText(" {{Edad (años)}}  ", "42 years");", "(" and ")" are the reason of your issue. Because in this case, those are used as a part of the regex. So how about the following modification?

From

NewFile.getBody().replaceText(" {{Edad (años)}}  ", "42 years");

To
NewFile.getBody().replaceText("{{Edad \\(años\\)}}", "42 years");

Reply all
Reply to author
Forward
0 new messages