Ali Hasan
Ali Hasan

Reputation: 162

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

Upvotes: 0

Views: 2253

Answers (2)

M Junaid
M Junaid

Reputation: 914

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

Upvotes: 2

Rick Kirkham
Rick Kirkham

Reputation: 9784

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.

Upvotes: 3

Related Questions