Shorten URLs in Google Documents

Panini has written an add-on for Google Documents that will automatically shorten all the hyperlinks (URLs) in the existing document using the bit.ly API. You’ll need to supply your own Bitly API key to be able to track clicks inside your Bitly dashboard.

A similar approach may be used to shorten links with goo.gl though you would need to enable the Google URL shorterner service from the services console.

function onOpen(e) {
  DocumentApp.getUi().createAddonMenu()
  .addItem("Shorten Links", 'displayLinks')
  .addToUi();
}

function onInstall(e) {
  onOpen(e);
}

function displayLinks() {

  var doc = DocumentApp.getActiveDocument();

  // Get the body text and find all links using regex
  var body = doc.getBody().getText();
  var links = body.match(/http[s]*:\/\/.+/g);
  var encoded = []
  var shortened = []
  var accessToken = "ENTER_YOUR_BITLY_TOKEN_HERE"

  for (i = 0; i < links.length; i++) {
    encoded.push(encodeURIComponent(links[i]))
    var getRequest = httpGet("https://api-ssl.bitly.com"+"/v3/shorten?access_token="+accessToken+"&longUrl="+encoded[i]);
    var jsonData = JSON.parse(getRequest)
    shortened.push("http://bit.ly/"+jsonData.data.hash+"\n")
    // Replace full links with shortened URLs
    DocumentApp.getActiveDocument().getBody().replaceText(links[i],shortened[i]);
  }
}

function httpGet(url)
{
   var http = UrlFetchApp.fetch(url)
   return http.getContentText();
}

Here’s another snippet by Dave Johnson that shortens URLs in Google Docs using the goo.gl service. It works for even ftp URLs and the good thing is that it ignores URLs that are already shortened.

function shortenUrl() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var text = body.getText();
  var pattern = new RegExp(/(http|ftp|https):\/\/(?!goo.gl)([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/g);
  var matches = text.match(pattern);
  if (matches != null) {
    for ( var x = 0 ; x < matches.length ; x++) {
      var match = matches[x];
      var url = UrlShortener.Url.insert({
        longUrl: match
      });

      body.replaceText(match, url.id);
    }
  }
}
Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

0

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.