This article explains how to implement the URI.js library into a Google Apps Script project.
URIjs.gs
eval(UrlFetchApp.fetch('https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.19.11/URI.min.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', );