且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Google Apps脚本-用弯角替换直引号

更新时间:2023-12-05 13:56:10

some1关于错误消息是正确的,但不幸的是,这并没有解决问题的根源:

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

在while循环结束时,使用变量 bodyString 查找要更改的引号的位置.问题在于bodyString只是一个字符串,因此每次对文档进行更改时我都需要对其进行更新.

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.

另一个更基本的问题是Google将\ n视为一个字符,因此我不得不将var testForLineBreaks = bodyString.slice(x-2, x);中的参数更改为x-1, x.

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.