Apps Script Doc word Counter App Example

Apps Script Doc word Counter App Example

Count the words within a Google doc using Google Apps Script code.

The code in this lesson will demonstrate how to use apps script within a bound script to select the text content from a Google Doc, and then use typical javascript methods to replace all the double and more than one space instances, and also then using the array split method to break the doc text content into an array using all the spaces in the document. Then output the result into the document either by appending a paragraph or by selecting the first paragraph and updating the text content of it.

function counter1() {

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

const docText = doc.getText();

const docText1 = docText.replace(/\s+/g,’ ‘);

const words1 = docText1.split(‘ ‘);

const topText = doc.getParagraphs()[0];

const wordValues = `Word Counter ${words1.length}`;



const newText = doc.appendParagraph(wordValues);