Reputation: 1309
I have been able to run the Github project Word-Add-in-JS-Redact successfully. Now, I need to make a change in the code. Need help for that.
At present the code finds multiple occurrences of a single string in a Word Doc and highlights those. But, I need to search multiple strings (can be hard coded inside the js file as well) in the document with a single button click, and highlight those. For example, I want to find both strings 'this'
and 'that'
in the document at the same time, and highlight them.
The current code, which searches for a single string:
Word.run(function (context) {
//search string
var searchInput = "hello";
// Search the document.
var searchResults = context.document.body.search(searchInput, {matchWildCards: true});
// Load the search results and get the font property values.
context.load(searchResults, "");
// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync()
.then(function () {
var count = searchResults.items.length;
// // Queue a set of commands to change the font for each found item.
for (var i = 0; i < count; i++) {
searchResults.items[i].font.highlightColor = '#FFFF00'; //Yellow
}
return count;
})
.then(context.sync)
.then(reportWordsFound);
A couple of ways I have tried so far with no luck:
Ran context.document.body.search(searchInput,
in a loop of the search strings, and tried to append the searchResults strings using +
and push
. This attempt gave an error saying, I cannot add multiple context results to a single object.
I tried to be creative with WildCards operators, but nothing was suitable for this. Many posts are talking about JS regex \(string1|string2/)
, but this seems to be invalid in Word context.
Upvotes: 1
Views: 442
Reputation: 1309
I could solve the problem at last, by creating a parent function, which calls the search function in a loop. My mistake was to create the loop inside the search function itself.
Here is the working code:
function searchStrings(){
searchString('hello world');
searchString('Goodbye');
}
RedactAddin.searchStrings = searchStrings;
function searchString(input) {
// Run a batch operation against the Word object model.
Word.run(function (context) {
//...... (same as the original) ...............
Upvotes: 1