使用 JS 在 Google Apps 脚本文档中查找未知字符串并将其更改为大写

wth*_*man 2 javascript regex google-apps-script

我在 Google Docs中的Fountain markdown http://fountain.io/中写道。喷泉是用来写剧本的。我想通过自动大写某些元素(打开或使用按钮,无论如何)使在喷泉中写作更友好一些。

这是一个格式正确的剧本(在喷泉中):

EXT. GAS STATION - DAY

Susie steps out of her car and walks toward the station attendant.

SUSIE
Hey, Tommy.

TOMMY
Where you been, Sue?  Come on in.

They walk toward the station entrance together.

INT. GAS STATION - NIGHT

etc...
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,编剧中有大量的大写锁定和移位操作,而且它变得乏味。

这就是为什么我想用小写(即int. gas station - day)编写并让 javascript/GAS 找到该文本并将其大写。与角色说话时相同:

susie
Hey, Tommy.
Run Code Online (Sandbox Code Playgroud)

会成为

SUSIE
Hey, Tommy.
Run Code Online (Sandbox Code Playgroud)

说话的角色总是在他们的名字上方有一个空行,下一行有文字。场景标题总是以 EXT 开头。或 INT。

到目前为止,我在 Stackoverflow 上得到了一些帮助,但我仍在努力让它发挥作用。我得到了一个很好的正则表达式字符串,它可以找到字符名称,但 GAS 的正则表达式实现有限。该正则表达式是[\n][\n]([^\n]+)[\n][^\n|\s]/gi. 我没有运气用正则表达式替换文本。我的 JS 技能是新生婴儿,但我已经完成了 CodeAcademy 的初学者 JS 课程,这是值得的。

我将不胜感激任何在正确方向上的帮助。

Mog*_*dad 5

要更改 Google Doc 中的文本,您需要获取各个元素并对其进行操作。在 Money Shot 之前,还有很多工作要做,深入研究文档:

paragraphText.toUpperCase();
Run Code Online (Sandbox Code Playgroud)

以下脚本是文档附加组件的一部分,可在此 gist中获得源代码,在changeCase.js.

代码.gs

/**
 * Scan Google doc, applying fountain syntax rules.
 * Caveat: this is a partial implementation.
 *
 * Supported:
 *  Character names ahead of speech.
 *
 * Not supported:
 *  Everything else. See http://fountain.io/syntax
 */
function fountainLite() {
  // Private helper function; find text length of paragraph
  function paragraphLen( par ) {
    return par.asText().getText().length;
  }

  var doc = DocumentApp.getActiveDocument();
  var paragraphs = doc.getBody().getParagraphs();
  var numParagraphs = paragraphs.length;

  // Scan document
  for (var i=0; i<numParagraphs; i++) {

    /*
    ** Character names are in UPPERCASE.
    ** Dialogue comes right after Character.
    */
    if (paragraphLen(paragraphs[i]) > 0) {
      // This paragraph has text. If the preceeding one was blank and the following
      // one has text, then this paragraph might be a character name.
      if ((i==0 || paragraphLen(paragraphs[i-1]) == 0) && (i < numParagraphs && paragraphLen(paragraphs[i+1]) > 0)) {
        var paragraphText = paragraphs[i].asText().getText();
        // If no power-user overrides, convert Character to UPPERCASE
        if (paragraphText.charAt(0) != '!' && paragraphText.charAt(0) != '@') {
          var convertedText = paragraphText.toUpperCase(); 
          var regexEscaped = paragraphText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); // http://stackoverflow.com/a/3561711/1677912
          paragraphs[i].replaceText(regexEscaped, convertedText);
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)