0

How can I insert a hyperlink on a particular word in a google-drive document?

I can find the word. After that, I want to assign a hyperlink. I used this code:

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

My doc is DocumentApp, and this works when done using the UI. However, the code above does not work. How can I perform this task?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275

1 Answers1

1

With the help of the utility function below, you can do this:

linkText("mot","https://developers.google.com/apps-script/class_text");

The linkText() function will find all occurrences of the given string or regex in text elements of your document, and wrap the found text with a URL. If the baseUrl includes a placeholder in the form of %target%, the placeholder will be replaced with the matching text.

To use from a custom menu, you need to further wrap the utility function, for example:

/**
 * 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%');
}

Code

I originally wrote this utility function to perform the task of wrapping bug numbers with links to our issue management system, but have modified it to be more general-purpose.

/**
 * 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);
  }
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275