【问题标题】:How to find a Word in a Document and insert a url如何在文档中查找单词并插入 url
【发布时间】:2013-03-22 22:49:20
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: google-apps-script google-docs


    【解决方案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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      相关资源
      最近更新 更多