Parse URL
by alekskorovin
JavaScript
function parseURL(URL) {
// Check if URL is not empty
if(URL === undefined || URL === null || URL.length === 0) {
return;
}
// Create a link in memory
var parser = document.createElement('a');
// Set attribute to parameter to make an object which URL can be automatically parsed by browser
parser.href = URL;
// Prepare an empty object for storing parsed parameters
var parsedURLObject = {};
// Make an array with list of names of available parameters which can be taken from given URL
var urlParts = ['protocol',
'hostname',
'port',
'pathname',
'search',
'hash',
'host'];
// Go through an array with names of parameters
for(part in urlParts) {
// Set property with name taken from an array
// to a value from 'parser' object which was automatically filled by browser
parsedURLObject[urlParts[part]] = parser[urlParts[part]];
}
// return object with all parameters filled from 'parser' object
return parsedURLObject;
}
// Now you can choose one of seven available parameters
console.log(parseURL('http://example.com:3000/pathname/?search=test#hash').hostname);