2016-04-12 45 views
1

我試圖用Google腳本中的單個文檔替換多個空格。但不幸的是,提供的解決方案to this question不適合我。正如你所看到的,我嘗試了幾種選擇,但無法弄清楚如何正確做到這一點。有任何想法嗎?Google Apps腳本 - 使用.replace方法刪除空格

function searchAndReplace() { 
 
    var body = DocumentApp.getActiveDocument() 
 
     .getBody(); 
 
    body.replaceText(/\s{2,}/,' '); 
 
    body.replaceText(/\s/g, " ") ; 
 
    body.replaceText("/\s/"," "); 
 
    body.replaceText('/\s{2,}/',' '); 
 
}

回答

1

嘗試:

function searchAndReplace() { 
    var body = DocumentApp.getActiveDocument().getBody(); 
    body.editAsText().replaceText('\\s*', ' '); 
} 

UPDATE

一種選擇是:

function getCorrections() { 
    var _getCorrections = 0, 
     text = DocumentApp.getActiveDocument().getBody().getText(), 
     regexp = /\s+/g, 
     matchesCorrections = text.match(regexp); 

    if (matchesCorrections) { 
    _getCorrections = matchesCorrections.reduce(function(previousValue, 
                 currentValue) { 
     return previousValue + currentValue.length - 1; 
    }, 0); 
    } 

    return _getCorrections; 
} 
+0

謝謝你的回答。有用!你介意添加一個顯示更正次數的報告嗎? – Thoran

+0

@Thoran:查看更新的答案。 – wchiquito

+0

如何在烘烤信息中顯示更正的數量?以及如何在菜單欄中添加此功能?隨意不回答,無論如何我都會給予獎勵。它需要24小時。 – Thoran