0

如何在 google-drive 文档中的特定单词上插入超链接?

我能找到这个词。之后,我想分配一个超链接。我使用了这段代码:

doc.editAsText().findText("mot").setLinkUrl("https://developers.google.com/apps-script/class_text");

我的文档是 DocumentApp,它在使用 UI 完成时有效。但是,上面的代码不起作用。我该如何执行此任务?

4

1 回答 1

1

借助下面的实用功能,您可以做到这一点:

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);
  }
}
于 2013-06-04T15:59:38.393 回答