1
votes

Here I am trying to search for text in context.document.body. I have a loop like this:

var searchList = ['foo','bar'];
while(i < searchList.length){
 Word.run(function(context) {
   var searchResults = context.document.body.search(searchList[i]);
         context.load(searchResults, 'text');
         context.trackedObjects.add(searchResults);
         return context.sync().then(function() {

It is not working.

1
HOW is it "not working". Please describe what kind of result you expect, and what it is you're actually getting. - Cindy Meister
I am getting the 'searchResults' for only first element ('foo') present in the searchList array and i am expecting result for both the element ('foo' , 'bar'). I did also console.log(i) before 'Word.run(function(context)' this line and unfortunately its logging 0 and 0 (though i++ is used); - Sk Asif
So that we can look into this, would you please post code that we can copy for testing rather than having to write it all out? See the following site Help topic for more information: stackoverflow.com/help/mcve - Cindy Meister

1 Answers

4
votes

You haven't provided enough code to give a precise answer but this is the code that does what you've described:

// Constuct your word array
let searchList = ['foo', 'bar'];

// Iterate through the word list
searchList.forEach(function (searchWord) {
    return Word.run(function (context) {

        // Tell word for search for a word
        let searchResult =
            context.document.body.search(searchWord);

        // Load the properties for the result
        context.load(searchResult);

        // Execute the batch
        return context.sync()
            .then(function () {

                // Loop through the results
                searchResult.items.forEach(function (result)
                { 
                    // Write them to the console
                    console.log(result.text);
                });                    
            });
    });
});