Share via

Office Add-in hangs on context.sync() when using wildcards in search

Nat B 1 Reputation point
2022-04-29T18:49:40.897+00:00

I'm trying to write an office plugin to find all telephone numbers and highlight them. I used the code template from the official documentation to write the following search with wildcards:

async function checkForText() {  
        // Run a batch operation against the Word object model.  
        await Word.run(async (context) => {  
  
            // Queue a command to search the document with a wildcard  
            // for any string of characters that starts with 'to' and ends with 'n'.  
            const searchResults = context.document.body.search('[0-9]@-', { matchWildcards: true });  
  
            // Queue a command to load the font property values.  
            searchResults.load('font');  
  
            // Synchronize the document state.  
            await context.sync();  
            console.log('Found count: ' + searchResults.items.length);  
  
            // Queue a set of commands to change the font for each found item.  
            for (let i = 0; i < searchResults.items.length; i++) {  
                searchResults.items[i].font.color = 'purple';  
                searchResults.items[i].font.highlightColor = 'pink';  
                searchResults.items[i].font.bold = true;  
            }  
  
            // Synchronize the document state.  
            await context.sync();  
        })  
    }  

The only line that I have modified is the search expression.

If I run this code on a single line of text it seems to work fine, but if I run it anything more the plugin hangs (forever) at the line await context.sync();. Weirdly, using just the wildcard expression '[0-9]@' finds all sequences of numbers in a large document with no issue. I've checked and '[0-9]@ ' with any character behind it hangs if there is a match to be found. If there's no match, it doesn't hang.

Any idea would be greatly appreciated!

Microsoft 365 and Office | Development | Other

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.