Google Apps Script Make text a clickable URL using replaceText()

后端 未结 1 1977
走了就别回头了
走了就别回头了 2021-01-05 10:52

I have this code that opens the file and replaces a string using replaceText.

var url = \'http://www.test.com\';
var doc = DocumentApp.openById(file.getId())         


        
相关标签:
1条回答
  • 2021-01-05 11:37

    Here is how it goes, at least if you have only one occurrence of the url placeHolder.

    If you have more than one then you should iterate the whole doc content to find each or them and replace them all.

    function myFunction() {
      var url = 'http://www.google.com';
      var doc = DocumentApp.getActiveDocument();// or DocumentApp.openById(file.getId()); as in your example code
      var element = doc.getBody().findText("<<urlGoesHere>>");
      if(element){ // if found a match
        var start = element.getStartOffset();
        var text = element.getElement().asText();
        text.replaceText("<<urlGoesHere>>",url);
        text.setLinkUrl(start, start+url.length, url);
        doc.saveAndClose();
      } // else do nothing
    }
    
    0 讨论(0)
提交回复
热议问题