Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

replace - Eliminate newlines in google app script using regex

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(" ",""); gives the error Invalid argument: searchPattern. I get the same error with text.replaceText(" ","");. The following attempts do nothing: text.replaceText("/ /","");, text.replaceText("/ /","");. 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("
","");

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("
","");
            }

            // Deal with fully selected text
            else {
                text.replaceText("
","");
            }
        }
    }
}

// No text selected
else {
    DocumentApp.getUi().alert('No text selected. Please select some text and try again.');
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (≡ 13) by the RE2 regex library used in most Google products.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...