3
votes

I am trying to write a google app script, which will find and replace specific words with others in google docs...

I would like " hello " (space, hello, space) to be replaced by " R1 " (space, R1, space) And if there is any punctuation mark after hello like a period, comma or question mark it should be the same logic:

  • " hello " to be replaced by " R1 "
  • " hello. " to be replaced by " R1. "
  • " hello, " to be replaced by " R1, "
  • " hello? " to be replaced by " R1? "

So I used the following:

function docReplace() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.replaceText(" hello ", " R1 ");
  body.replaceText(" hello. ", " R1. ");
  body.replaceText(" hello, ", " R1, ");
  body.replaceText(" hello? ", " R1? ");
}

Unfortunately this doesn't work, as "." , "," and "?" are regex symbols.

Then, I tried this:

function docReplace() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.replaceText(" hello ", " R1 ");
  body.replaceText(" hello\. ", " R1. ");
  body.replaceText(" hello\, ", " R1, ");
  body.replaceText(" hello\? ", " R1? ");
}

But still doesn't work. Commas and Question marks return as periods.

I would appreciate if anyone could help with the correct code.

1

1 Answers

2
votes
  • You want to achieve the following replacement using Google Apps Script. In this sample, ## was used as the separator of the values.

    • From

      ## hello ##
      ## hello. ##
      ## hello, ##
      ## hello? ##
      
    • To

      ## R1 ##
      ## R1. ##
      ## R1, ##
      ## R1? ##
      

If my understanding is correct, how about this modification? In this modification, \., \, and \? are modified to \\., \\, and \\?, respectively.

Modified script:

function docReplace() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.replaceText(" hello ", " R1 ");  // Modified
  body.replaceText(" hello\\. ", " R1. ");  // Modified
  body.replaceText(" hello\\, ", " R1, ");  // Modified
  body.replaceText(" hello\\? ", " R1? ");  // Modified
}

Reference:

If I misunderstood your question and this was not the result you want, I apologize.