如何在google驱动器文档中的特定单词上插入超链接?
我能找到这个词。之后,我想分配一个超链接。我用了这段代码:
doc.editAsText().findText("mot").setLinkUrl("https://developers.google.com/apps-script/class_text");
我的文档是DocumentApp,这在使用UI完成时有效。但是,上面的代码不起作用。我该如何执行此任务?
答案 0 :(得分:0)
在下面的效用函数的帮助下,您可以这样做:
linkText("mot","https://developers.google.com/apps-script/class_text");
linkText()
函数将在文档的文本元素中找到所有出现的给定字符串或正则表达式,并使用URL包装找到的文本。如果baseUrl
包含%target%
形式的占位符,则占位符将替换为匹配的文字。
要从自定义菜单中使用,您需要进一步包装效用函数,例如:
/**
* Find all ISBN numbers in current document, and add a url Link to them if
* they don't already have one.
* Add this to your custom menu.
*/
function linkISBNs() {
var isbnPattern = "([0-9]{10})"; // regex pattern for ISBN-10
linkText(isbnPattern,'http://www.isbnsearch.org/isbn/%target%');
}
我最初编写此实用程序函数来执行包含错误编号的任务,其中包含指向我们的问题管理系统的链接,但已将其修改为更通用的。
/**
* Find all matches of target text in current document, and add a url
* Link to them if they don't already have one. The baseUrl may
* include a placeholder, %target%, to be replaced with the matched text.
*
* @param {String} target The text or regex to search for.
* See Body.findText() for details.
* @param {String} baseUrl The URL that should be set on matching text.
*/
function linkText(target,baseUrl) {
var doc = DocumentApp.getActiveDocument();
var bodyElement = DocumentApp.getActiveDocument().getBody();
var searchResult = bodyElement.findText(target);
while (searchResult !== null) {
var thisElement = searchResult.getElement();
var thisElementText = thisElement.asText();
var matchString = thisElementText.getText()
.substring(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive()+1);
//Logger.log(matchString);
// if found text does not have a link already, add one
if (thisElementText.getLinkUrl(searchResult.getStartOffset()) == null) {
//Logger.log('no link')
var url = baseUrl.replace('%target%',matchString)
//Logger.log(url);
thisElementText.setLinkUrl(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(), url);
}
// search for next match
searchResult = bodyElement.findText(target, searchResult);
}
}