📜  google docs api 字数统计 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:12.284000             🧑  作者: Mango

代码示例1
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;
}