Search code examples
google-apps-scriptgoogle-sheetsspreadsheetgoogle-docsgoogle-docs-api

bulk find and replace with a condition case match and exact match google app script,doc,sheet


Thank you in advance.

I have a sheet with data as follows.

Find Replace condition
Page number ten Page No. 10 match case
Page number 10 Page No. 10 match case
ms Ms exact match

I want to find and replace text in docs with the condition. The below code works fine for me but whenever ex. Williams it replace with WilliaMs.

function replMyText() {
  var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
  var sh = ss.getSheetByName('find and replace');
  var doc = DocumentApp.getActiveDocument();
  var rgtxt = doc.getBody();
  var rgrep = sh.getRange('A2:B103');
  var repA = rgrep.getValues().filter(r => r.every(c => c.toString()));
  repA.forEach(e => rgtxt.replaceText(...e));
}

Solution

  • We need capture group of regex for properly capturing all cases, not just words between spaces. (e.g. ms. “ms” ms, ms! ms? ms! ‘ms’)

    But since replaceText doesnt support capture group while replace does, we need to derive it using replace inside replaceText.

    EDIT:

    Code:

    function replMyText() {
      var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
      var sh = ss.getSheetByName('find and replace');
      var doc = DocumentApp.getActiveDocument();
      var rgtxt = doc.getBody();
      var rgrep = sh.getRange('A2:C103');
      var repA = rgrep.getValues().filter(r => r.every(c => c.toString()));
    
      // Search per paragraph so it won't produce exponential copies per paragraph
      var paragraphs = rgtxt.getParagraphs();
      for (var i = 0; i < paragraphs.length; i++) {
        repA.forEach(function(e){
          if(e[2] == "match case") {
            DocumentApp.getActiveDocument().getBody().replaceText(e[0], e[1]);
          }
          else if (e[2] == "exact match") {
            // Only replace the string in between non [a-zA-Z0-9_]
            // Capture string including 2 \W characters around it, then pad them around the replaced string
            var replace = "(\\W)" + e[0] + "(\\W)";
            var re = new RegExp(replace, "g");
            var text = paragraphs[i].getText();
            paragraphs[i].replaceText(".*", text.replace(re, "$1" + e[1] + "$2"));
    
            // Replace the ones starting in a paragraph if present
            replace = "^" + e[0] + "(\\W)";
            re = new RegExp(replace, "g");
            text = paragraphs[i].getText();
            paragraphs[i].replaceText(".*", text.replace(re, e[1] + "$1"));
          }
        });
      }
    }
    

    Latest update tests:

    sample3

    Latest update output:

    output2

    References: