Reputation: 11
I am trying to replace dots "." with other strings in a google document using Google apps script.
My code below does not seem to do anything. Do you have any idea why ? (EDIT : it now does something)
Many thanks !
var body = DocumentApp.getActiveDocument().getBody();
body.replaceText(".", "mmmmm"); // EDIT replace any literal character
body.replaceText("\.", "mmmmm"); // EDIT : replacement done !
Upvotes: 1
Views: 176
Reputation: 21910
You need to double the backslashes "\\."
.
Try this:
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
console.log( body.getText() );
body.replaceText("\\.", "xyz");
console.log( body.getText() );
}
If the input is this:
Some text. More. done
Then the output will be this:
Some textxyz Morexyz done
Additional notes
When you provide your regex inside a string "..."
, then this needs to account for the fact that string literals can contain escape characters, where the \
has a specific meaning (the start of an escape sequence).
For example, in "foo\tbar"
the \t
is a tab character.
To counteract this special meaning of \
in a string literal, you must first escape the \
, so that it can then be used by the regular expression correctly - as a regular expression escape character and not as a string literal escape character.
Upvotes: 3