Word Counter

80 views
Skip to first unread message

Lucas Dadalt

unread,
Aug 5, 2022, 3:18:00 PM8/5/22
to Google Apps Script Community
Hi!
I am looking to use native Word Counter from Google Docs, is that possible?
I tried using this code but it doesn't count properly:

function myFunction() { 
var space = " "; 
var text = DocumentApp.getActiveDocument().getBody().getText(); 
var words = text.replace(/\s+/g, space).split(space); 
Logger.log(words.length); 
}

Can somebody help?
Thanks in advance

Ben Ronkin

unread,
Aug 26, 2022, 11:35:12 PM8/26/22
to Google Apps Script Community
I tried your code on my own document and the count was over by one. 

So I added: Logger.log(words) and saw that one of the array elements was a space.

So I tweaked the code to: var words = text.replace(/\s+/g, space).split(space).filter(Boolean);

And now it was the right count.

If you inspect the words array then you can see where the  problems are and then try to improve your text.replace.

Ben

Lucas Dadalt

unread,
Aug 29, 2022, 2:10:40 PM8/29/22
to google-apps-sc...@googlegroups.com
Thanks! I will try to implement that solution :)

--
You received this message because you are subscribed to a topic in the Google Groups "Google Apps Script Community" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-apps-script-community/Qze1FSRdnC0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/cf7cb2b9-f115-4647-b5c4-f6847bd440e4n%40googlegroups.com.


--
Reply all
Reply to author
Forward
0 new messages