Google Apps Script to create a custom function that cleans and formats text in a Google Docs document

Here’s a basic example that removes extra spaces and trims the text:

function cleanText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  
  // Get the text from the document
  var text = body.getText();
  
  // Clean and format the text
  text = text.replace(/\s+/g, ' '); // Remove extra spaces
  text = text.trim(); // Trim leading and trailing spaces
  
  // Update the document with the cleaned text
  body.setText(text);
}

To use this script:

  1. Open your Google Docs document.
  2. Click on “Extensions” in the top menu and then select “Apps Script.”
  3. Replace any code in the script editor with the provided code.
  4. Save the project.
  5. Click the Play button (▶️) to run the cleanText function.

This script will clean the text by removing extra spaces and trimming leading and trailing spaces. You can modify the cleanText function to include other text cleaning operations as needed. Remember to save and run the script whenever you want to clean the text in your Google Docs document.