9

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?

migrated from superuser.com Nov 6 '16 at 7:57

This question came from our site for computer enthusiasts and power users.

7

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);
}    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.