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 = parser.search.replace(/^\?/, '').split('&');
	for( i = 0; i < queries.length; i++ ) {
		split = queries[i].split('=');
		searchObject[split[0]] = split[1];
	}

	return {
		protocol: parser.protocol,
		host: parser.host,
		hostname: parser.hostname,
		port: parser.port,
		pathname: parser.pathname,
		search: parser.search,
		searchObject: searchObject,
		hash: parser.hash
	};

}
Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.