文書中の単語をONLYOFFICEマクロで置換する方法

2023年11月01日著者:Denis

ドキュメントの編集は日常業務の基本であり、繰り返し行う作業の負担を軽減するツールに憧れることはよくあります。このブログ記事では、選択範囲内の文書内の単語を置換するマクロをご紹介します。

Replace words in the document with ONLYOFFICE macro

マクロの構築

まず、ドキュメントエディタで現在のファイルにアクセスします。そして、選択されたテキストを対象とし、値を取り込みます。この範囲は、単語を検索して置き換えるためのものです:

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メソッドの豊富なライブラリは、皆さまのアイデアを現実に変える鍵です。ご質問や革新的なコンセプトがあれば、ぜひ私たちと共有してください。皆さまのご意見は高く評価され、コラボレーションを楽しみにしております。