Rss feed

JavaScript URL Parser

For science reasons I decided to write a simple JavaScript URL Parser this morning. The basic idea behind the function is to make it easier to extract the bits of a URL your interested in, be it the Port,  Host,  Protocol or even the value of a parameter in the query string.

/**
 * URL Parse
 * A quick URL parsing function for JavaScript
 * @version 0.4
 * @author Carl Saggs
 */
function urlParse(url){
	var self = {};
	//Store full url
	self.url = url;
	//array to store params
	self.QueryParams = new Array();
	//Use DOM to get URL basics
	self.a = document.createElement('a');
	self.a.href = url;
	//Parse Query String
	q_seg = self.a.search.substring(1).split('&');
	for(i=0; i<q_seg.length;i++){
		s = q_seg[i].split('=');
		self.QueryParams[s[0]] = s[1];
	}
	//Extract the Port
	self.port = url.split('/')[2].split(':')[1];

	//Return Protocol in use
	self.getProtocol = function(){
		return self.a.protocol;
	}
	//Return Host
	self.getHost = function(){
		return self.a.host.split(':')[0];//Remove the port from the end
	}
	//Return Port
	self.getPort = function(){
		//Assume default port if none is set
		return  (self.port == null)
				? ((self.getProtocol=='https:')?443:80) 
				: self.port; 
	}
	//Return Path
	self.getPath = function(){
		return self.a.pathname;
	}
	//Get full Query String
	self.getQueryString = function(){
		return self.a.search;
	}
	//Get Query String as Array
	self.getQueryArray = function(){
		return self.QueryParams;
	}
	//Get value of parameter in query string
	self.getQueryParam = function(x){
		return self.QueryParams[x];
	}
	//Return original URL
	self.getURL = function(){
		return self.url;
	}
	//Get Fragment
	self.getFragment = function(){
		return self.a.hash.substring(1);//Remove # from start
	}

	//Return self
	return self;
}

The function is designed to be pretty straight forward to use, calling the function will return the object containing all of the URLs attributes which can then be accessed by the provided get Methods. An additional advantage to having the function return an object is that you can chain the functions when it seems appropriate (as in the final example below).

//Usage Demo
var test = urlParse("http://www.sub.domain.com:1337/test/sample.php?queryArg1=Hello&queryArg2=Goodby");
alert(test.getQueryParam('queryArg2')); // "goodbye"
alert(test.getPort()); // "1337"
alert(test.getHost()); // "www.sub.domain.com"
alert(test.getPath()); // "/test/sample.php"
//Alterntive usage
alert(urlParse("http://test.com:17/?a=Cake&b=Cheese").getQueryParam('a')); // "Cake"

Anyways, hopefully someone will find it helpful 🙂

Feel free to request additional features / notify me of any bugs in the comments. You can now also find it on my GitHub.

[Edit: 2011/10/07] The source code has been updated to fix the scoping bug mentioned by Rikky.


4 Responses to “JavaScript URL Parser”

  1. Rikki Loades says:

    October 7th, 2011 at 2:36 pm

    The way you assign stuff to this inside the urlParse function and return it is actually pretty dangerous. With how you are calling it, “this” in that context gets set to the Javascript “head” object – basically window. This means you are writing the variables into window and then returning window.

    Why is this bad?…

    Say you did the following:

    var test = urlParse(“http://example.com”);
    var test2 = urlParse(“http://example2.com”);

    alert(test.getHost()); // “example2.com”
    alert(test2.getHost()); // “example2.com”

    console.log(window === test) // true
    console.log(test === test2) // true

    You either need to create a closure and freeze dry the url in a “hoisted” set of local variables or construct an object with the new keyword.

  2. Carl says:

    October 7th, 2011 at 3:18 pm

    Yikes, totally didn’t notice I was writing in to the global scope o.o Will fix when i get home.

  3. IT support says:

    December 23rd, 2011 at 9:54 am

    var test = urlParse(“http://www.sub.domain.com:1337/test/sample.php?queryArg1=Hello&queryArg2=Goodby”);
    alert(test.getQueryParam(‘queryArg2’)); // “goodbye”
    alert(test.getPort()); // “1337”
    alert(test.getHost()); // “www.sub.domain.com”
    alert(test.getPath()); // “/test/sample.php”
    //Alterntive usage
    alert(urlParse(“http://test.com:17/?a=Cake&b=Cheese”).getQueryParam(‘a’)); // “Cake”

  4. Carl says:

    January 14th, 2012 at 4:51 pm

    @IT Support: What’s the trouble you seem to be having?

Leave a Reply