Microsoft Office 加载项 javascript:按 matchPrefix:true 搜索 - 如何获取匹配前缀的完整词

Microsoft Office add-in javascript: search by matchPrefix:true- how to get the full word for the matched prefix

我正在尝试关注这篇文章here

此外,在此处添加代码,因为链接总是可以移动、修改或关闭。

    // Run a batch operation against the Word object model.
    Word.run(function (context) {

    // Queue a command to search the document based on a prefix.
    var searchResults = context.document.body.search('pattern', {matchPrefix: 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));
    }
});

它工作正常,但我没有得到完整的反馈。 因此,如果单词是 patternABCDEFGH,则通过

匹配 searchResults 中的单词
var text = searchResults.items[i].text;
console.log('Matching text:' + text);

我得到的只有 pattern,我如何得到完整的单词?

选项 MatchPrefix 不会搜索以该字母组合开头的每个单词 - 它仅搜索位于单词开头的字母组合。所以在这种情况下它只会找到字符 "pattern" 而不是整个 "patternMatching" 或 "patternABCDEFGH".

正如 Juan 提到的,为了获得以特定字母组合开头的整个单词,您需要 Word 的正则表达式变体:通配符搜索。

通配符模式如下所示:[P,p]attern*>

这假设您需要大写和小写 "p",后跟任何字符,直到单词结束。

    var searchResults = context.document.body.search('[P,p]attern*>', {matchWildcards: true});