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

1.9k views Asked by At

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));
                    }
                });
2

There are 2 answers

2
Rick Kirkham On BEST ANSWER

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.

0
J i N On

     Word.run(function (context) {
      
         var selection = context.document.getSelection();

       
         context.load(selection, 'text');

        
         return context.sync().then(function () {
            
             console.log('Selected Text:', selection.text);
         });
     }).catch(function (error) {
         console.error('Error: ' + JSON.stringify(error));
     });