2016-04-12 46 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