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 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 though you would need to enable the Google URL shorterner service from the services console.

function onOpen(e) {
  .addItem("Shorten Links", 'displayLinks')
function onInstall(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++) {
    var getRequest = httpGet(""+"/v3/shorten?access_token="+accessToken+"&longUrl="+encoded[i]);
    var jsonData = JSON.parse(getRequest)
    // Replace full links with shortened URLs
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 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):\/\/(?![\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/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