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

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

问题描述

我有这段代码可以打开文件并使用 replaceText 替换字符串.

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();

当我打开文档时,发生了替换,但 url 不是可点击的超链接,它只是静态文本.有没有办法以编程方式使其成为可点击的链接?

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 programmatically make it a clickable link?

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

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)

有什么想法吗?

推荐答案

这是怎么回事,至少如果你只有一个 url placeHolder 出现.

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 Script 使用 replaceText() 使文本成为可点击的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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