URL parsing using native JS engine approach

The snippet bellow can come in handy when you need basic URL parsing


/**
 * @description URL parsing using native JS engine approach
 * @param {string} url - URL string
 * @returns {object} parsed data
 */

function parseURL(url) {
	var parser = document.createElement('a');
	parser.href = url;
	return {
		protocol : parser.protocol, // => "http:"
		hostname : parser.hostname, // => "domain.com"
		port : parser.port, // => "8000"
		pathname : parser.pathname, // => "/path/"
		search : parser.search, // => "?search=test"
		hash : parser.hash, // => "#hash"
		host : parser.host // => "domain.com:8000"
	}
}

console.dir(parseURL("http://domain.com:8000/path/?search=test&bar=1&bar=2&key1=val1#hash"));
  • 0
  • October 10, 2016, 10:38pm
  • t0lkman

Comments (0)

RSS Collapse / Expand

Only registered and authorized users can leave comments. Login or Register