从Doc Body获取文本字符串并保留换行符

时间:2017-07-06 13:57:48

标签: google-apps-script

我有一个Google文档,文档中包含以下内容:

Hello
Replace me
Line 2

我正在尝试更换"替换我"包括换行符,"我被替换为\ n with 2 lines"使最终的Doc内容相等:

Hello
I am replaced
with 2 linesLine 2

我的代码很简单:

function myFunction() {
  var searchString = 'Replace me\n';
  var newString = 'I am replaced\nwith 2 lines';
  var stringData = DocumentApp.getActiveDocument().getBody();
  stringData.replaceText(searchString, newString);
}

我尝试将searchString更改为使用\\n\v<br><br/>以及其他一些项目。

我需要包含哪些searchString才能包含换行符?

以下是sample file with script

1 个答案:

答案 0 :(得分:0)

function myFunction() {
  var searchStringNoLineBreak = 'Replace me';
  var searchStringRegex = "Replace me\\v";
  var substring = "I am replaced\nwith 2 lines";

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

  // get all paragraphs
  var paragraphs = body.getParagraphs();

  // loop paragraphs
  for (var i = 0; i < paragraphs.length; i++)
  {
    // current paragraph
    var p = paragraphs[i];

    // if found text with soft return, replace it
    if (p.findText(searchStringRegex))
    {
      p.replaceText(searchStringRegex, substring);
    }

    var isAtTheEnd = p.findText(searchStringNoLineBreak);

    // if text without newline was found but at the end of paragraph, we need to replace it too
    if (isAtTheEnd)
    {
      // replace text without new line character
      p.replaceText(searchStringNoLineBreak, substring);

      // then merge next paragraph with current to remove that new line between them
      if (i+1 < paragraphs.length)
      {
        var nextP = paragraphs[i+1];
        nextP.merge();
      }
    }
  }
}

输入:

enter image description here

结果:

enter image description here