更换Stings,Index(-1)值必须大于或等于零。

时间:2014-07-25 12:53:39

标签: javascript google-apps-script

在替换template文件中的字符串以生成报告时,我的应用程序脚本中出现以下错误。

Index (-1) value must be greater or equal to zero.

该功能如下所示。

/**
* Search a String in the document and replaces it with the generated newString, and sets it Bold
*/
function replaceString(doc, String, newString) {

  var ps = doc.getParagraphs();
  for(var i=0; i<ps.length; i++) {
    var p = ps[i];
    var text = p.getText();
    //var text = p.editAsText();

    if(text.indexOf(String) >= 0) {
      //look if the String is present in the current paragraph
      //p.editAsText().setFontFamily(b, c, DocumentApp.FontFamily.COMIC_SANS_MS);
      p.editAsText().replaceText(String, newString);

      // we calculte the length of the string to modify, making sure that is trated like a string and not another ind of object.
      var newStringLength = newString.toString().length;

      // if a string has been replaced with a NON empty space, it sets the new string to Bold,
      Logger.log([newString,newStringLength]);
      if (newStringLength > 0) {
        // re-populate the text variable with the updated content of the paragraph
        text = p.getText();
        Logger.log(text);
        p.editAsText().setBold(text.indexOf(newString), text.indexOf(newString) + newStringLength - 1, true);
      }
    }
  } 
}

出错时

[newString,newStringLength] = [ The Rev Levels are at ZGS 003 on the electric quality standard. The part has a current change to ZGS 005!,108]

有人有任何建议吗?

提前致谢, 迈克尔

1 个答案:

答案 0 :(得分:0)

您没有处理字符串不存在的情况。因此indexOf返回-1并使用它。也不要使用像String这样的保留字来表示变量名。

相关问题