I am working on a word add-in project for Office JS. I have been trying to implement the specific word highlight using my tool. So when a user selects any word from my tool it will get selected on the word document based on it's paragraph index.
The problem I am facing is that if there are multiple instances of the same word say "fox" in the same paragraph it only highlights the first instance and ignores all the other instances.
I have implemented it like can anyone help me solve this problem. I want to select the specific word from N number of same words in the same paragraph
async function highlight(updateText) {
if(!globalAction) return
IS_HIGHLIGHTING = true
try {
await Word.run(async (context) => {
if(!updateText) return
const { word, paragraphIndex } = updateText;
const targetParagraph =await loadParagraph(context,paragraphIndex)
if (targetParagraph) {
let range = targetParagraph.getRange("Whole");
let textRanges = range.getTextRanges([" "], true);
textRanges.load("items");
await context.sync();
highlightOrReplaceMatchingPhrases(textRanges, word, "highlight");
await context.sync();
} else {
console.log("No matching paragraph found.");
}
})
}catch(err){
console.log(err);
} finally {
setTimeout(()=> IS_HIGHLIGHTING = false, 500)
};
}
function highlightOrReplaceMatchingPhrases(textRanges, word, action, replacementText = "") {
let cleanedWord = cleanWord(word);
let wordsArray = cleanedWord.split(" ");
let matchingRanges = [];
textRanges.items.forEach((item, i, arr) => {
if (i + wordsArray.length > arr.length) {
return;
}
let matchFound = true;
for (let j = 0; j < wordsArray.length; j++) {
if (cleanWord(arr[i + j].text) !== wordsArray[j]) {
matchFound = false;
break;
}
}
if (matchFound) {
let phraseRange = arr[i].expandTo(arr[i + wordsArray.length - 1]);
matchingRanges.push(phraseRange);
}
});
if (matchingRanges.length > 0) {
let finalRange = matchingRanges[0];
if (action === "highlight") {
finalRange.select();
} else if (action === "replace") {
finalRange.insertText(replacementText, "Replace");
finalRange.select()
updateDocumentCharacterLength()
}
} else {
console.log("No matching text found.");
}
}