Search code examples
ms-wordoffice-jsoffice-web-app

How to perform some operation on selected text of a word document using Office JS API?


I need to get the selected text from the word document and highlight some specific words of it using Office JavaScript API. I am able to get the selected text so far but unable to highlight the specific words in the selected text.

PS: I am able to highlight the text in the whole document body, all I need to do is to highlight the text within the selected range. Here's the code for highlighting the words in the whole document.

Word.run(function (context) {
                context.load(context.document.body, 'text')
                return context.sync().then(function () {
                    for (var i = 0; i < item.words.length; i++) {

                        var searchResults = context.document.body.search(item.words[i], { ignorePunct: true, matchCase: false, matchWholeWord: true });

                        context.load(searchResults, 'font');

                        return context.sync().then(function () {

                            for (var i = 0; i < searchResults.items.length; i++) {
                                searchResults.items[i].font.color = color;
                                searchResults.items[i].font.highlightColor = "#F0F0F0";
                                searchResults.items[i].font.bold = true;
                            }

                            return context.sync();
                        });
                    }
                });

            })
               .catch(function (error) {
                    console.log('Error: ' + JSON.stringify(error));
                    if (error instanceof OfficeExtension.Error) {
                        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
                    }
                });

Solution

  • You just need to get the range of the selected text and then apply your logic to it.

    Replace this line context.load(context.document.body, 'text') with these two lines:

    var selectedRange = context.document.getSelection();
    context.load(selectedRange, "text");
    

    Then replace context.document.body in the 5th line with selectedRange.