Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* A variable that stores the ID of the Google Document. */
- const DOCUMENT_ID = "YourDocIDGoesHere";
- /* The ID of the Google Sheet that you want to write the word count to. */
- const SHEET_ID = "YourSheetIDGoesHere";
- /**
- * It counts the words in a Google Document and writes the word count to a Google Sheet.
- */
- function countWords() {
- /* Opening the Google Document with the ID of DOCUMENT_ID. */
- const document = DocumentApp.openById(DOCUMENT_ID);
- /* Setting the word count to 0. */
- let wordCount = 0;
- /* Config for the headings and titles in the document to be excluded them from the word count.
- * This is the same functionality that Google Docs uses for wordcount */
- const searchType = DocumentApp.ElementType.PARAGRAPH;
- const searchHeadings = [
- DocumentApp.ParagraphHeading.HEADING1,
- DocumentApp.ParagraphHeading.HEADING2,
- DocumentApp.ParagraphHeading.HEADING3,
- DocumentApp.ParagraphHeading.HEADING4,
- DocumentApp.ParagraphHeading.HEADING5,
- DocumentApp.ParagraphHeading.HEADING6,
- DocumentApp.ParagraphHeading.TITLE
- ];
- let searchResult = null;
- /* Searching for the headings and titles in the document and excluding them from the word count. */
- while (
- (searchResult = document.getBody().findElement(searchType, searchResult))
- ) {
- const par = searchResult.getElement().asParagraph();
- if (searchHeadings.includes(par.getHeading())) {
- /* Subtracting the number of words in the heading from the word count. */
- wordCount -= par.getText().split(" ").length;
- }
- }
- /* Get all the paragraphs in the document. */
- const paragraphs = document.getBody().getParagraphs();
- /* Loops through all the paragraphs in the document and adds the word count of each paragraph to
- the total word count. */
- for (const paragraph of paragraphs) {
- /* Getting the text of the paragraph. */
- const paragraphText = paragraph.getText();
- /* It splits the paragraph text into an array of words and then counts the number of words in the
- array. */
- wordCount += paragraphText.split(" ").length;
- }
- /* It opens the Google Sheet with the ID of SHEET_ID. */
- const sheet = SpreadsheetApp.openById(SHEET_ID);
- /* Writing the word count to the first cell of the first sheet in the Google Sheet.
- * you can change this to place it whever you need to place the wordcount*/
- const firstSheet = sheet.getSheets()[0];
- const firstCell = firstSheet.getRange("A1");
- firstCell.setValue(wordCount);
- }
Advertisement
Add Comment
Please, Sign In to add comment