DEV Community

Dev365
Dev365

Posted on

Search and highlight text using word add-in

If you want to search the word document for text and need to highlight with a color, following code can be used
This code sample searches for the text "Office" and ignores punctuation. If the text is found, the matches are bolded, highlighted in yellow, and the font color set to purple.

 // Run a batch operation against the Word object model.
Word.run(function (context) {
  // Queue a command to search the document and ignore punctuation.
  var searchResults = context.document.body.search('Office', {ignorePunct: true});

  // Queue a command to load the search results and get the font property values.
  context.load(searchResults, 'font');

  // Synchronize the document state by executing the queued commands,
  // and return a promise to indicate task completion.
  return context.sync().then(function () {
      console.log('Found count: ' + searchResults.items.length);

      // Queue a set of commands to change the font for each found item.
      for (var i = 0; i < searchResults.items.length; i++) {
        searchResults.items[i].font.color = 'purple';
        searchResults.items[i].font.highlightColor = '#FFFF00'; // Yellow
        searchResults.items[i].font.bold = true;
      }

      // Synchronize the document state by executing the queued commands,
      // and return a promise to indicate task completion.
      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));
  }
});

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
rishabh0211 profile image
Rishabh Rastogi

Hi @dev365
I've a similar use case where I need to highlight multiple texts in the word document. But I also need to listen if the user clicks on any of the highlighted region. Is there a way to do ths?