1

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,}/',' ');
}
Community
  • 1
  • 1
SebastianB
  • 95
  • 1
  • 8

1 Answers1

3

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;
}
wchiquito
  • 16,177
  • 2
  • 34
  • 45
  • Thanks for the answer. It works! Would you mind adding a report showing number of corrections? – Thoran Apr 19 '16 at 13:14
  • how do I display the number of corrections like in a toast message? and how do I add this functionality in the menu bar? Feel free to not answer it, I will grant the bounty anyways. It takes 24 hours. – Thoran Apr 20 '16 at 05:14
  • @Thoran: See [Dialogs and Sidebars in Google Apps](https://developers.google.com/apps-script/guides/dialogs) and [Custom Menus in Google Apps](https://developers.google.com/apps-script/guides/menus). – wchiquito Apr 20 '16 at 05:56