I'm trying to write part of an add-on for Google Docs that eliminates newlines within selected text using replaceText
. The obvious text.replaceText("\n","");
gives the error Invalid argument: searchPattern
. I get the same error with text.replaceText("\r","");
. The following attempts do nothing: text.replaceText("/\n/","");
, text.replaceText("/\r/","");
. I don't know why Google App Script does not allow for the recognition of newlines in regex.
I am aware that there is an add-on that does this already, but I want to incorporate this function into my add-on.
This error occurs even with the basic
DocumentApp.getActiveDocument().getBody().textReplace("\n","");
My full function:
function removeLineBreaks() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only deal with text elements
if (element.getElement().editAsText) {
var text = element.getElement().editAsText();
if (element.isPartial()) {
text.replaceText("\n","");
}
// Deal with fully selected text
else {
text.replaceText("\n","");
}
}
}
}
// No text selected
else {
DocumentApp.getUi().alert('No text selected. Please select some text and try again.');
}
}
It seems that in replaceText
, to remove soft returns entered with Shift-ENTER, you can use \v
:
.replaceText("\\v+", "")
If you want to remove all "other" control characters (C0, DEL and C1 control codes), you may use
.replaceText("\\p{Cc}+", "")
Note that the \v
pattern is a construct supported by JavaScript regex engine, and is considered to match a vertical tab character (≡ \013
) by the RE2 regex library used in most Google products.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With