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 is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

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

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

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

We will never send any spam emails. Promise 🫶🏻