regexgoogle-apps-scriptgoogle-docs

Remove spaces using .replace method


I'm trying to replace multiple whitespaces with single ones in a Google Doc with a script. But unfortunately the provided solution to this question isn't working for me. As you can see, I tried several alternatives but can not figure out how to do it right. Any ideas?

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

Solution

  • Try:

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

    UPDATE

    One option is:

    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;
    }