Skip to content Skip to sidebar Skip to footer

Google Apps Script---Replace Straight Quotation Marks With Curly Ones

When I was typing a novel on my Google Docs iPad app, it used straight up-and-down quotation marks, like this: '. Now, I want to change all of these quotes to the curly kind, witho

Solution 1:

I am not sure about the exact limit, but I think you can include a counter in your while loop, and for every 50 or 100, output that via Logger.log(); once you get hold of that limit count, you may do what being suggested,

i.e. when approaching the limit, flush/save the changes by calling Document.saveAndClose(), then start again with the main loop by reopening the document with Document.openById()


Solution 2:

some1 was right about the error message, but unfortunately that did not get to the root of the problem:

At the end of my while loop, the variable bodyString was being used to find the location of quotation marks to change. The problem was that bodyString was just that, a string, and so I needed to update it each time I made a change to the document.

Another problem, albeit more basic, was that Google counts \n as one character, so I had to change the parameter in var testForLineBreaks = bodyString.slice(x-2, x); to x-1, x.

After tinkering with these issues, my finished code looked like this:

function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();

  //Replace quotes that are not at beginning or end of paragraph
  body.replaceText(' "', ' “');
  body.replaceText('" ', '” ');

  var bodyString = body.getText();
  var x = bodyString.indexOf('"');
  var bodyText = body.editAsText();

  while (x != -1) {
    var testForLineBreaks = bodyString.slice(x-1, x);

    if (testForLineBreaks == '\n') { //testForLineBreaks determines whether it is the beginning of the paragraph
      //Replace quotes at beginning of paragraph
      bodyText.deleteText(x, x);
      bodyText.insertText(x, '“');
    } else {
      //Replace quotes at end of paragraph
      bodyText.deleteText(x, x);
      bodyText.insertText(x, '”');
    }

    body = DocumentApp.getActiveDocument().getBody();
    bodyString = body.getText();
    x = bodyString.indexOf('"');
    bodyText = body.editAsText();
  }
}

There is one remaining problem with the code. If the quote is at the very beginning of the document, as in the first character, then the script will insert the wrong quote style. However, I plan on fixing that manually.


Post a Comment for "Google Apps Script---Replace Straight Quotation Marks With Curly Ones"