How to parse URLs in Google Apps Script?

Viewed 2425

I have a GAS project and I need to parse some URLs into their hostname and pathname properties as follows.

Code.gs
const url = new URL( 'http://www.example.com/cats', );
const { hostname,  pathname, } = url;

Here are some docs on the above URL constructor method. [1] | [2]

The above code produces the following error.

Error message:

ReferenceError: URL is not defined (line 64, file "Code")

What am I missing? How can I parse my URLs using GAS?

2 Answers

This article explains how to implement the URI.js library into a Google Apps Script project.

URIjs.gs
eval(UrlFetchApp.fetch('https://rawgit.com/medialize/URI.js/gh-pages/src/URI.js').getContentText());

// Get the URL protocol (eg. 'https' or 'http')
function urlProtocol(url){
  return URI(url).protocol()
}

// Get the URL hostname (eg. 'googleappscripting.com')
function urlHostname(url){
  return URI(url).hostname()
}

// Get the whole URL path (eg. '/some/directory/filename.png')
function urlPath(url){
  return URI(url).path()
}

// Get the URL directory (eg. '/some/directory')
function urlDirectory(url){
  return URI(url).directory()
}

// Get the URL file name (eg. 'filename.png')
function urlFilename(url){
  return URI(url).filename()
}

// Get the URL query string (eg. 'this=1&that=2')
// If a query string parameter is provided as the second argument
// then the function will return the value of that parameter
function urlQuery(url,param){
  if (param !== undefined){
    var queryMap = URI(url).query(true);
    return queryMap[param]
  }
  return URI(url).query()
}

// Get the URL hash (eg. '#section-two')
function urlHash(url){
  return URI(url).hash()
}

// Check to see if a URL is a fully qualified URL
function urlIsUrl(url){
  return URI(url).is('url')
}

// Check to see if a URL is a fully qualified IP Address
function urlIsIp(url){
    return URI(url).is('ip')
}


// Test function to ensure that each of the above functions do what they are supposed to do.
function testURI() {

  var testUrl = 'https://googleappscripting.com/some/test/page.html?this-is=helpful&it=works#rad';  
  var funcTests = [
    urlProtocol,
    urlHostname,
    urlDirectory,
    urlPath,
    urlFilename,
    urlQuery,
    urlHash,
    urlIsUrl,
    urlIsIp
  ]

  // Check that each function returns the expected value
  funcTests.forEach(function(test){
    Logger.log(test(testUrl))
  });

  // Extra check to see that the urlQuery function works with a query parameter argument
  Logger.log(urlQuery(testUrl,'it'));

}

Then in my code, as follows:

Code.gs
const hostname = URIjs.urlHostname( 'http://www.example.com/cats', );
Related