google docs api word count code example

Example: google docs api word count

function countWords() {
    var s = DocumentApp.getActiveDocument().getBody().getText();
    //this function kept returning "1" when the doc was blank 
    //so this is how I stopped having it return 1.       
    if (s.length === 0) 
        return 0;
    //A simple \n replacement didn't work, neither did \s not sure why
    s = s.replace(/\r\n|\r|\n/g, " ");
    //In cases where you have "...last word.First word..." 
    //it doesn't count the two words around the period.
    //so I replace all punctuation with a space
    var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()"?“”]/g," ");
    //Finally, trim it down to single spaces (not sure this even matters)
    var finalString = punctuationless.replace(/\s{2,}/g," ");
    //Actually count it
    var count = finalString.trim().split(/\s+/).length; 
    return count;
}

Tags:

Misc Example