How to retrieve the word count using Google Apps Script for Google Docs?

I am looking for a way to obtain the word count from a Google Document using Google Apps Script. I’m trying to write a report with a specific word count requirement of between 1,800 and 2,000 words. Unlike MS Word, where the word count is conveniently visible in the status bar, I want to achieve something similar in Google Docs. Writing a function that extracts the document’s text multiple times to compute the word count seems inefficient and unnecessary, yet I haven’t been able to find a built-in function that accomplishes this in the Google Docs script reference. The keyboard shortcut Ctrl+Shift+C brings up a window with the word count, so I suspect there is a way to access this count programmatically. After spending several hours searching for a solution without success, I would greatly appreciate any assistance.

hey! while there’s no direct function to get the word count in Apps Script, u can extract the content and split it by spaces to count. i know it’s not super efficient but it works for now! hope this helps! :slight_smile:

In Google Apps Script, while there’s no direct API for retrieving the word count, you can utilize the getText() method of the DocumentApp to extract all the text from your Google Doc. Once you have the text, use JavaScript split functionality to split the text based on spaces or other delimiters and count the resulting array elements to determine the word count. Though this approach involves processing the entire document content, it effectively provides the word count that you might be looking for programmatically.

Another approach is to leverage the Google Docs API itself for a more streamlined way, though this requires more setup. By using the DocumentApp.getActiveDocument().getBody().getText() method, you can access the document’s body text and manage your word count calculations via JavaScript. You have the advantage of writing custom logic to exclude specific parts or count particular sections. It may not be faster, but it definitely offers flexibility in custom handling depending on the type of content management and word granularity you require.