stackoverflow: Convert URL into its simplest form
//////////////////////////////////
// https://stackoverflow.com/questions/54472715/js-convert-url-into-its-simplest-form/
//////////////////////////////////
require('url');
function getBaseUrl(url){
const u = new URL(url);
const result =`${u.host}${u.pathname}`
.split('//').join('/')
.replace('www.', '');
// cut off the trailing '/' character from the result
if (result.length && result[result.length - 1] === '/')
return result.substring(0, result.length - 1)
return result;
}
// Test:
const urls = [
"https://website.com/coolpage/938921/",
"https://www.website.com/coolpage/938921/",
"http://website.com/coolpage/938921/",
"https://website.com/coolpage/938921/",
"https://website.com/coolpage/938921/?awesome=1",
"https://website.com/coolpage/938921?awesome=1",
"https:///website.com//coolpage//938921//"
];
for (let i = 0; i < urls.length; i++) {
const u = getBaseUrl(urls[i]);
console.log(`${i}: ${u}`);
}
no comments