Finding text (multiple times) and highlighting

前端 未结 4 1059
青春惊慌失措
青春惊慌失措 2020-12-03 12:44

I would like to find all the instances of a word in a Google doc and highlight them (or comment - anything so it stands out). I have created the following function, but it o

4条回答
  •  时光说笑
    2020-12-03 13:09

    Ok so, chaining your codes it could finish like this :

    function findWordsAndHighlight() {
    var doc = DocumentApp.openById("DocID");
    var text = doc.editAsText();
    var search = "searchTerm";
    var index = -1;
    var color ="#2577ba";
    var textLength = search.length-1;
    
    while(true)
     {
       index = text.getText().indexOf(search,index+1);
       if(index == -1)
         break;
       else text.setForegroundColor(index, index+textLength,color );
     }
    
    };
    

    I still have a doubt. This code works nice, but why I have to use search.length-1?

提交回复
热议问题