借助下面的实用函数,您可以做到这一点:
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);
}
}