最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

office365 - How to find and highlight the exact word in Office JS word plugin - Stack Overflow

programmeradmin3浏览0评论

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

}

发布评论

评论列表(0)

  1. 暂无评论