How to Add a New Line After Each Question Mark in Google Docs Using Google Apps Script

Have you ever found yourself needing to format a document by adding a new line after every question mark (?)? If so, doing it manually can be tedious and time-consuming — especially for large documents. Fortunately, with the power of Google Apps Script, you can automate this task in seconds.

In this blog post, you’ll learn how to create an Apps Script that scans the entire content of a Google Doc, identifies every question mark (?), and inserts a new line after it. This is a perfect use case for automating repetitive formatting tasks.


Why Use Google Apps Script for Document Formatting?

Google Apps Script allows users to automate Google Workspace applications like Google Docs, Sheets, and Drive. By using a simple JavaScript-like syntax, you can create scripts that interact with documents, modify their content, and improve productivity.

This script is particularly useful if you:

  • Regularly edit documents with large amounts of text.
  • Need to break long paragraphs into more readable chunks.
  • Work on scripts for content formatting or proofreading.

The Code

Here’s the complete code to add a new line after each question mark in a Google Doc:

function addNewLineAfterQuestionMarks() {
try {
// Open the active Google Doc
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();

// Get the entire text of the document
let text = body.getText();

// Replace each '?' with '?\n' to add a newline after every question mark
const updatedText = text.replace(/\?/g, '?\n');

// Set the updated text back into the document
body.setText(updatedText);

Logger.log('New lines added after each question mark.');
} catch (error) {
Logger.log('Error: ' + error.message);
}
}

How It Works

Let’s break down each part of the code to understand how it achieves the task.

1. Open the Active Document

const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();

This part opens the currently active Google Doc. DocumentApp.getActiveDocument() returns the document you’re working on, and doc.getBody() accesses the main content of the document.

2. Get the Text of the Document

let text = body.getText();

Once we have the document body, we extract all its text using body.getText(). This returns the complete text of the document as a single string.

3. Replace ‘?’ with ‘?\n’

const updatedText = text.replace(/\?/g, '?\n');

Here’s where the magic happens. We use JavaScript’s .replace() method with a regular expression to find every instance of ? and replace it with ?\n.

Explanation of the Regex:

  • /\?/g: Matches every question mark (?). The backslash (\) escapes the ?, and the g flag ensures that all occurrences are replaced (not just the first one).
  • '?\n': This tells the script to replace each ? with ? followed by a newline (\n).

4. Update the Document

body.setText(updatedText);

After we format the text, the script updates the document’s content with body.setText(updatedText). This replaces the original text with the new formatted version.

5. Log Success or Error Messages

Logger.log('New lines added after each question mark.');

If everything runs smoothly, a success message is logged. If an error occurs, the script catches it and logs the error message.


How to Use This Script

To use this script, follow these simple steps:

  1. Open a Google Doc where you want to apply this formatting.
  2. Go to ExtensionsApps Script. This will open the Apps Script editor.
  3. Delete any existing code in the editor and paste the script provided above.
  4. Click the 💾 Save button (or press Ctrl + S / Cmd + S).
  5. Click the ▶️ Run button (or select RunaddNewLineAfterQuestionMarks from the menu).
  6. Grant the necessary permissions if prompted.

Once you run the script, you’ll notice that every instance of ? in your document is followed by a new line. No manual editing is required!


Practical Example

Imagine you have the following text in your Google Doc:

What is your name? Where do you live? Do you like coffee?

After running the script, it will be transformed into:

What is your name?
Where do you live?
Do you like coffee?

Notice that a new line has been inserted after each question mark.


Customization Ideas

This script is simple but powerful. Here are some ways you can customize it:

  • Custom Characters: Instead of adding new lines after ?, you could add new lines after any character, such as !, . or :.javascriptCopy codeconst updatedText = text.replace(/!|\.|:/g, '$&\n'); This regex looks for !, ., or : and adds a newline after them.
  • Custom Line Breaks: If you want two line breaks after each ?, you can change ?\n to ?\n\n:javascriptCopy codeconst updatedText = text.replace(/\?/g, '?\n\n');
  • Conditional Replacement: If you only want to add new lines after certain types of questions (like those starting with “Why” or “How”), you could modify the script to check for patterns like:javascriptCopy codeconst updatedText = text.replace(/(Why|How).+?\?/g, '$&\n');

Common Issues and How to Fix Them

If you encounter any issues running the script, here’s a list of possible problems and solutions.

IssueCauseSolution
Script not runningPermissions not grantedClick Review Permissions and grant access.
Error: Document not openNo active document openOpen a Google Doc before running the script.
Wrong formattingRegex not working as expectedDouble-check the regex to ensure it matches ?.
Replaces partial textOnly part of the document is affectedMake sure the entire document is selected with body.getText().

When Should You Use This Script?

Here are some real-world use cases for this script:

  • Content Editing: Separate questions for readability in quizzes, FAQ pages, or scripts.
  • Educational Documents: In e-learning materials, ensure each question appears on its own line.
  • Copywriting: Reformat marketing or content review documents with multiple calls-to-action.