Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created April 2, 2024 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/7de3ed734ac9b103631c3a20452dca74 to your computer and use it in GitHub Desktop.
Save tanaikech/7de3ed734ac9b103631c3a20452dca74 to your computer and use it in GitHub Desktop.
Convert Soft Breaks to Hard Breaks on Google Documents using Google Apps Script

Convert Soft Breaks to Hard Breaks on Google Documents using Google Apps Script

Description

This script converts soft breaks to hard breaks in a Google Document using Google Apps Script.

Usage

Follow these steps:

1. Create a New Google Document

Create a new Google Document and open it. Go to "View" -> "Show non-printing characters" in the top menu to see line breaks in the document body (as shown in the image below).

2. Sample Script

Copy and paste the following script into the script editor of your Google Document.

Important: Before using this script, enable the Google Docs API in Advanced Google services. Ref

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const requests = [
    { replaceAllText: { replaceText: "\n", containsText: { text: "\u000b" } } },
  ];
  Docs.Documents.batchUpdate({ requests }, doc.getId());
}
  • The script searches for soft breaks using \u000b.
  • It replaces them with \n, which creates hard breaks.

Testing

Running the script on a sample document with soft breaks will convert them to hard breaks as follows.

Note

  • The soft breaks can be searched with findText("\\v"). But, when replaceText("\\v", '\n') is run, it seems that \n is used as the soft breaks. I'm not sure whether this is the current specification or a bug. From this situation, I thought that Google Docs API might be able to be used. But, it seems that Google Docs API cannot search the soft breaks with \v. So, I thought that \u000b might be able to be used.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment