如何用 ONLYOFFICE 宏替换文档中的单词

2023年11月02日作者: Mona

我们平时会非常多的进行文档编辑,也希望有能减轻重复性琐事负担的工具。在这篇文章中,我们将构建一个宏,替换所选内容中文档中的单词。

如何用 ONLYOFFICE 宏替换文档中的单词

构建宏

首先,我们在文档编辑器中访问当前文件。然后,我们定位选定的文本并捕获值。这个范围是我们打算查找和替换单词的地方:

const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const rawText = oRange.GetText();

然后我们删除选定的文本:

oRange.Delete();

我们将要查找的单词分配给变量 wordToFind,并将要替换的单词分配给 replacementWord

// Define the word to find and the word to replace it with
const wordToFind = "oldWord"; // Replace "oldWord" with the word you want to find
const replacementWord = "newWord"; // Replace "newWord" with the word you want to replace it with

我们对 rawText(选定范围内的文本)应用正则表达式来查找 wordToFind 的所有实例,并将它们替换为 replacementWord。带有“g”标志的正则表达式可确保替换所有出现的情况。修改后的文本存储在cleanedText变量中:

// Use regular expression to find and replace the word
const cleanedText = rawText.replace(new RegExp(wordToFind, "g"), replacementWord);

查找和替换完成后,我们使用 Api.CreateParagraph() 在文档中创建一个新段落。在本段中,我们添加带有替换单词的文本。最后我们将修改后的段落插入到文档中:

// Insert the cleanedText with the original paragraph structure
const oParagraph = Api.CreateParagraph();
oParagraph.AddText(cleanedText);
oDocument.InsertContent([oParagraph]);

整个宏如下:

(function()
{
const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const rawText = oRange.GetText();
oRange.Delete();
// Define the word to find and the word to replace it with
const wordToFind = "oldWord"; // Replace "oldWord" with the word you want to find
const replacementWord = "newWord"; // Replace "newWord" with the word you want to replace it with
// Use regular expression to find and replace the word
const cleanedText = rawText.replace(new RegExp(wordToFind, "g"), replacementWord);
// Insert the cleanedText with the original paragraph structure
const oParagraph = Api.CreateParagraph();
oParagraph.AddText(cleanedText);
oDocument.InsertContent([oParagraph]);
})();

现在让我们运行我们的宏,看看它是如何工作的!

我们希望这个宏能作为您实用的辅助工具,并简化您的文档编辑。ONLYOFFICE 宏旨在将您的工作流程提升到新的高度。

不要错过利用 ONLYOFFICE API 强大功能的机会。我们丰富的 API 方法库是将您的想法变为现实的关键。如果您有任何问题或创新概念,欢迎与我们分享。您的意见非常有价值,我们很高兴能够与您合作。祝探索之路好运!