Search code examples
replacegoogle-apps-scriptgoogle-docs

Find and Replace in a loop in Google Docs App Script


I frequently write research papers that require in-text citations as numbers in brackets - for example: "This is a quote [1]."

As I write the papers, I use letters instead of numbers so I can find & replace later, since I'm likely to add in citations here and there, I don't want to have to renumber every citation to keep them in order.

How do I search through an entire Google doc in a loop, and replace each letter with a number? E.G. replace [a] with [1], [b] with [2] etc. I tried this code, but it replaced every single character in the doc with a random number in brackets. I'm not clear on the rules for escaping brackets, so I've also tried this with a \ before every bracket:

function myFunction() {

    var doc = DocumentApp.getActiveDocument();
    body = doc.getBody();

     var alphabet = ["[a]", "[b]", "[c]", "[d]", "[e]", "[f]", "[g]", "[h]", "[i]", "[j]", "[k]", "[l]", "[m]", "[n]", "[o]", "[p]", "[q]", "[r]", "[s]", "[t]", "[u]", "[v]", "[w]", "[x]", "[y]", "[z]", "[aa]", "[bb]", "[cc]", "[dd]", "[ee]", "[ff]", "[gg]", "[hh]", "[ii]", "[jj]", "[kk]", "[ll]", "[mm]", "[nn]", "[oo]", "[pp]", "[qq]", "[rr]", "[ss]", "[tt]", "[uu]", "[vv]", "[ww]", "[xx]", "[yy]", "[zz]"]; 
      
      for (i = 0; i < alphabet.length; i++) { 
       num = i+1;
       newText = "["+num+"]";
    
    body.replaceText(alphabet[i], newText);
    }
}

Solution

  • Looks like you need to double-escape the brackets:

    function testReplace(){
      var doc = DocumentApp.getActiveDocument();
      body = doc.getBody();
    
    
      var alphabet = ["\\[a\\]", "\\[b\\]", "[c]"]; // c is a test-case
    
    
      for (i = 0; i < alphabet.length; i++) { 
        num = i+1;
        newText = "["+num+"]";
    
        body.replaceText(alphabet[i], newText);
      }
    }
    

    Before:

    A a [a]
    
    B b [b]
    
    C c [c]
    

    After:

    A a [1]
    
    B b [2]
    
    C [3] [[3]]