1

I have a document where I need to find a text or word, each time i run a function the selection has to go to next if a word or text is found. If it is at the end it should take me to top in a circular way just like find option in notepad.

Is there a way to do it?

I know about findText(searchPattern, from) but I do not understand how to use it.

contributorpw
  • 4,739
  • 5
  • 27
  • 50
user3436029
  • 75
  • 1
  • 2
  • 13
  • Where is the question? This is formatted almost like a request, which is not the nature of this community. If you have tried to do something, it is not working, and you have tried to fix/debug it. Post your code, any errors you are receiving, and information on what you have tried. – Douglas Gaskell Apr 25 '16 at 09:50
  • You can simply use Javascript substring function, can you include your document and its format? – Amir Apr 25 '16 at 11:27

1 Answers1

1

There are several wrappers and classes in the DocumentApp. They help to work with the contents of the file.

It is necessary to understand carefully what they are responsible. In your case the code below should be work fine:

function myFunctionDoc() {

    // sets the search pattern
    var searchPattern = '29';

    // works with current document 
    var document = DocumentApp.getActiveDocument();

    // detects selection
    var selection = document.getSelection();

    if (!selection) {
        if (!document.getCursor()) return;
        selection = document.setSelection(document.newRange().addElement(document.getCursor().getElement()).build()).getSelection();
    }
    selection = selection.getRangeElements()[0];

    // searches
    var currentDocument = findNext(document, searchPattern, selection, function(rangeElement) {
        // This is the callback body
        var doc = this;
        var rangeBuilder = doc.newRange();
        if (rangeElement) {
            rangeBuilder.addElement(rangeElement.getElement());
        } else {
            rangeBuilder.addElement(doc.getBody().asText(), 0, 0);
        }
        return doc.setSelection(rangeBuilder.build());
    }.bind(document));

}

// the search engine is implemented on body.findText
function findNext(document, searchPattern, from, callback) {
    var body = document.getBody();
    var rangeElement = body.findText(searchPattern, from);
    return callback(rangeElement);
}

It looks for the pattern. If body.findText returns undefined then it sets on top of the document.

I have a gist about the subject https://gist.github.com/oshliaer/d468759b3587cfb424348fa722765187

contributorpw
  • 4,739
  • 5
  • 27
  • 50