テキスト編集の領域では、不要なスペースを削除する効率的なマクロが不可欠です。それは生産性を高め、ワークフローを合理化します。このブログ記事では、選択したテキストから余分なスペースを削除するように設計されたONLYOFFICEマクロの作成方法をご紹介します。
マクロの構築
まず、アクティブなドキュメントにアクセスし、選択されたコンテンツをキャプチャします:
const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const rawText = oRange.GetText();
次に、選択したテキストを削除します。後で、余分な空白のない整形されたテキストに置き換えられます:
oRange.Delete();
改行文字に基づいて、rawTextを段落の配列に分割します。段落配列の各要素は、元のテキストの段落を表します:
// Split the original word into an array of paragraphs based on newline characters
const paragraphs = rawText.split('\n');
ループは次に、段落配列の各段落を繰り返し処理し、連続する空白を半角空白に置き換えることで段落を削除します。削除された段落は、cleanedParagraphs 配列に格納されます:
const cleanedParagraphs = [];
// Clean each paragraph and store it in the cleanedParagraphs array
for (const paragraph of paragraphs) {
// Use a regular expression to replace consecutive whitespaces with a single space
const cleanedParagraph = paragraph.replace(/\s+/g, ' ');
cleanedParagraphs.push(cleanedParagraph);
}
各段落をクリーニングした後、join(‘ \n’) メソッドを使用して、クリーニングされた段落を 1 つの文字列に結合します。テキストを文書に挿入する場合、適切な段落区切りのある単一の文字列を提供する必要があるため、このステップは非常に重要です:
// Join the cleaned paragraphs back together with newline characters
const cleanedText = cleanedParagraphs.join('\n');
最後に、新しい段落(oParagraph)を作成し、cleanedTextを文書に挿入します。このcleanedTextには、クリーニングされたすべての段落が、元の段落構造を保持するための改行文字とともに、1つの文字列にまとめられています:
// Insert the cleanedText with original paragraph structure
const oParagraph = Api.CreateParagraph();
oParagraph.AddText(cleanedText);
oDocument.InsertContent([oParagraph], { "KeepTextOnly": true });
マクロコード全体は以下のとおりになります:
(function()
{
const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const rawText = oRange.GetText();
oRange.Delete();
// Split the original word into an array of paragraphs based on newline characters
const paragraphs = rawText.split('\n');
// Create an array to store cleaned paragraphs
const cleanedParagraphs = [];
// Clean each paragraph and store it in the cleanedParagraphs array
for (const paragraph of paragraphs) {
// Use a regular expression to replace consecutive whitespaces with a single space
const cleanedParagraph = paragraph.replace(/\s+/g, ' ');
cleanedParagraphs.push(cleanedParagraph);
}
// Join the cleaned paragraphs back together with newline characters
const cleanedText = cleanedParagraphs.join('\n');
// Insert the cleanedText with original paragraph structure
const oParagraph = Api.CreateParagraph();
oParagraph.AddText(cleanedText);
oDocument.InsertContent([oParagraph], { "KeepTextOnly": true });
})();
マクロを実行し、どのように機能するか見てみましょう!
このマクロがあなたのツールキットの貴重な資産となり、生産性を新たな高みへと合理化することを願っています。ONLYOFFICEマクロは、生産性向上の可能性を解き放ち、効率的で自動化されたソリューションを提供します。
マクロ作成に踏み出す一方で、ONLYOFFICE APIによって利用可能になる可能性を見逃してはいけません。ご質問や革新的なアイディアがありましたら、遠慮なくコメントや私たちにご連絡ください。