Google Docs – How to Make Hundreds of URLs Clickable

google docsgoogle-apps-script

I am migrating documents to Google Docs that contain many URLs. If I hit Enter after each one, the link becomes clickable. But I'm looking for a way to convert all URLs (text starting with http:// or https://) to be clickable.

Is there a macro, add-on or script I could run?

Best Answer

I did some research on using Google Apps Scripts and I came up with this script that works for my needs. I hope it's useful for someone else too.

function onOpen() {
  DocumentApp.getUi().createAddonMenu()
    .addItem('Make URLs Clickable', 'makeUrlsClickable')
    .addToUi();
}

function makeUrlsClickable() {
  var urlRegex = 'http[s]?:\/\/[^ ]+';
  var body = DocumentApp.getActiveDocument().getBody();
  var urlElement = body.findText(urlRegex);  

  while (urlElement != null) {    
    var urlText = urlElement.getElement().asText();

    var startOffset = urlElement.getStartOffset();
    var endOffset = urlElement.getEndOffsetInclusive();

    urlText.setLinkUrl(startOffset, endOffset, getOnlyUrl(urlText.getText()));

    urlElement = body.findText(urlRegex, urlElement);
  }
}

function getOnlyUrl(text) {
  var startOffset = text.indexOf('http');
  var endOffset = text.indexOf(' ', startOffset);

  if (endOffset === -1) {
    endOffset = text.length;
  }

  return text.substring(startOffset, endOffset);
}