在搜索操作期间无法替换文本

Not able to replace text during search operation

本文关键字:替换 文本 搜索 操作      更新时间:2023-09-26

我目前正在使用office-js api搜索word文档,并找到正在放置在word doc中的令牌的所有实例。然而,当我试图替换匹配的令牌时,我得到了debug.errorlocation = "Range.insertParagraph"。似乎操作应该按照编写的方式工作,但是当找到搜索结果时,它不会替换所需的单词。

示例字符串

 Our strategy is to consider ~~client~~​'s​ business needs, and our audit will spec​​ifically focus on these related key factors:

        Word.run(function (context) {
        var content = contentObject.Content.replace(/<img[^>"']*((("[^"]*")|('[^']*'))[^"'>]*)*>/g, "");
        var range = context.document.getSelection().insertHtml(content, Word.InsertLocation.replace);
        var paragraphs = context.document.body.paragraphs;
        var clientName;
        paragraphs.load(paragraphs, range, 'text');
        return context.sync().then(function () {
            for (var x = 0; x < paragraphs.items.length; x++) {
                var paragraph = paragraphs.items[x];
                var styleType = paragraphs.items[x].text.toString().match(/~~([^]*?)~~/g);
                if (paragraphs.items[x].text.search("~~") >= 0 && styleType[0] != "~~/picture~~") {
                    var styleValue = styleType[0].toString().replace(/[']~~)}[{(]/g, '').trim();
                    paragraph.style = styleValue;
                }
                if(paragraphs.items[x].style === "/Title Page Client Name")
                {
                    var name = paragraphs.items[x].text;
                    clientName = name;
                }
            }
            return context.sync().then(function () {
                var searchResults = context.document.body.search('~~client~~', { ignoreSpace: true });
                context.load(searchResults);
                return context.sync().then(function () {
                    for (var i = 0; i < searchResults.items.length; i++) {
    error location>>  searchResults.items[i].insertParagraph(clientName, Word.InsertLocation.replace);
                    }
                    clientName = "";
                })
            })
        })
        .then(context.sync)
        .then(cleanTags())
        .catch(function (error) {
            feedBackMessage(error.description);
        })
    });
};

Ok,导致我错误的问题是我正在使用.insertParagraph,其中单词api期望插入段落而不仅仅是一个单词。我认为这是了不起的,这个api设计得足够好,可以实际检测段落和简单的文本插入。为了记录,如果有人要插入文本(只是一个单词),他们将需要使用.insertText

<

措辞代码/strong>

 return context.sync().then(function () {
                var searchResults = context.document.body.search('~~client~~', { ignoreSpace: true });
                context.load(searchResults);
                return context.sync().then(function () {
                    for (var i = 0; i < searchResults.items.length; i++) {
                        searchResults.items[i].insertText(clientName, Word.InsertLocation.replace);
                    }
                    clientName = "";
                    return context.sync().then(function () {
                    })
                })
            })