Google Apps脚本使用replaceText()将文本设为可点击的网址 [英] Google Apps Script Make text a clickable URL using replaceText()

查看:142
本文介绍了Google Apps脚本使用replaceText()将文本设为可点击的网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码打开文件并使用replaceText取代了一个字符串。

  var url ='http:// www.test.com; 
var doc = DocumentApp.openById(file.getId());
doc.replaceText(<< urlGoesHere>>,url);
doc.saveAndClose();

当我打开文档时,替换已经发生,但url不是可点击的超链接,它是只是静态文本。有没有一种方法可以将程序设置为可点击的链接?



我发现这种名为setLinkUrl的文本方法,但没有文档/示例: https://developers.google.com/apps-script/reference/document/text#setLinkUrl (字符串)



任何想法? 这是怎么回事,至少如果你只有一个URL placeHolder的发生。



如果你有多个,那么你应该迭代整个文档内容来找到每个或他们并全部替换它们。

  function myFunction(){
var url ='http:// www .google.com';
var doc = DocumentApp.getActiveDocument(); //或DocumentApp.openById(file.getId());如您的示例代码
var element = doc.getBody()。findText(<< urlGoesHere>>);
if(element){//如果找到匹配
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
}


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());
doc.replaceText("<<urlGoesHere>>", url);
doc.saveAndClose();

When I open the doc, the replacement has occured, but the url is not a clickable hyperlink, it's just static text. Is there a way to programatticaly make it a clickable link?

I found this method of text called setLinkUrl, but there's no documentation/examples: https://developers.google.com/apps-script/reference/document/text#setLinkUrl(String)

Any ideas?

解决方案

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
}

这篇关于Google Apps脚本使用replaceText()将文本设为可点击的网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆