In terms of text editing, it is necessary to have a macro that can efficiently remove excess spaces, which can improve work efficiency and simplify workflows. In this blog post, we will guide you in creating an ONLYOFFICE macro to remove excess spaces from the selected text.



Build macro

We first access the activity document and capture the selected content:

Then delete the selected text. Afterwards, the corresponding part will be replaced by formatted text without any extra spaces:


We divide "rawText" into a paragraph array based on line breaks. Each element of the paragraph array represents a paragraph in the original text:


Then, loop through each paragraph in the paragraph array, and replace and clean with a single space for areas with consecutive spaces. The cleaned paragraphs are stored in the "cleanedParagraphs" array:



After cleaning each paragraph, we use the "join ('\ n')" method to merge the cleaned paragraphs into a single string, where each cleaned paragraph is separated by a new line character "(\ n)". This step is crucial because when inserting text into a document, we need to provide a single string with appropriate delimiters:



Finally, we create a new paragraph "(oParagraph)" and insert "cleanedText" into the document. This "cleanedText" contains all cleaned paragraphs, merged into a single string, and added with a line break to preserve the original paragraph structure:



The complete code for this macro is as follows:




We hope that this macro can quickly become a valuable asset in your arsenal, elevating your work efficiency to new heights. You can use the ONLYOFFICE macro to obtain efficient and automated solutions, improve efficiency, and unleash unlimited potential.

As you explore how to write macros, don't forget the unlimited possibilities provided by the ONLYOFFICE API. If you have any questions or new ideas, please feel free to leave a comment or contact us to share them. We value your insights very much and look forward to working with you. Good luck on your exploration journey!