javascriptgoogle-apps-scriptgoogle-docs-apimethod-signatureline-by-line

google docs boldText until semicolon line by line app script error


function boldTextInLines() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var text = body.getText();

  var lines = text.split("\n"); 

  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var endPos = line.indexOf(':');
    console.log(endPos);
    
    if (endPos !== -1) {
      
      body.editAsText().setBold(i, 0, endPos, true);
    }else{
      console.log(endPos);
    }
    
  }
}

Exception: The parameters (number,number,number,(class)) don't match the method signature for DocumentApp.Text.setBold. boldTextInLines @ Kod.gs:14

This is the error that was thrown and how can I correct it?


Solution

  • function boldTextInLines() {
      var doc = DocumentApp.getActiveDocument();
    
      var body = doc.getBody();
    
      var text = body.getText();
     
    
      var lines = text.split("\n"); 
      console.log(lines)
      
      for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        console.log(line)
        var endPos = line.indexOf(":");
        console.log(endPos);
    
        
        if (endPos!==-1) {
    
          var textBeforeColon = line.substring(0, endPos);
          var startIndex = body.getText().indexOf(textBeforeColon);
          var endIndex = startIndex + textBeforeColon.length;
          console.log(textBeforeColon)
          body.editAsText().setBold(startIndex,endIndex, true);
        }else{
    
        }
        
      }
    }

    firstly, setBold should be setBold(startPos,endPos,true) secondly, when the code runs, up to ":" the words will not be bold, since the first "endPos" parameter represents a different position within the line rather than the document, the expected result wouldn't be achieved even if you correct it. An adjusted version of the setBold function with correct start and end positions is included in the code.