Parsing URLs in JavaScript

There's an excellent trick to parsing URLs in JavaScript, which was introduced last year by John Long over on GitHub. This technique works great, but the resulting search property will be a raw query string. This isn't very useful if you need to access certain variables in said query string. Thus, the following function expands on this paradigm, providing an additional property that contains an object based on the original query string.

function parseURL(url) {

	var parser = document.createElement('a'),
		searchObject = {},
		queries, split, i;

	// Let the browser do the work
	parser.href = url;

	// Convert query string to object
	queries =^\?/, '').split('&');
	for( i = 0; i < queries.length; i++ ) {
		split = queries[i].split('=');
		searchObject[split[0]] = split[1];

	return {
		protocol: parser.protocol,
		hostname: parser.hostname,
		port: parser.port,
		pathname: parser.pathname,
		searchObject: searchObject,
		hash: parser.hash

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.