Remove extra spaces
Removes extra spaces in text document.
(function()
{
let doc = Api.GetDocument();
let range = doc.GetRangeBySelect();
let rawText = range.GetText();
range.Delete();
// Split the original word into an array of paragraphs based on newline characters
let paragraphs = rawText.split('\n');
// Create an array to store cleaned paragraphs
let cleanedParagraphs = [];
// Clean each paragraph and store it in the cleanedParagraphs array
for (let paragraph of paragraphs) {
// Use a regular expression to replace consecutive whitespaces with a single space
let cleanedParagraph = paragraph.replace(/\s+/g, ' ');
cleanedParagraphs.push(cleanedParagraph);
}
// Join the cleaned paragraphs with newline characters
let cleanedText = cleanedParagraphs.join('\n');
// Insert the cleanedText into the original paragraph structure
let paragraph = Api.CreateParagraph();
paragraph.AddText(cleanedText);
doc.InsertContent([paragraph], { "KeepTextOnly": true });
})();
Methods used: GetDocument, GetRangeBySelect, GetText, Delete, CreateParagraph, AddText, InsertContent
Reference Microsoft VBA macro code
Sub RemoveExtraSpaces()
Dim rng As Range
' Set the range to the entire document
Set rng = ActiveDocument.Content
' Replace multiple spaces with a single space
rng.Text = Replace(rng.Text, " ", " ")
MsgBox "Extra spaces removed!", vbInformation
End Sub