steveosoule
4/27/2015 - 6:54 PM

JavaScript URL Parser Helper

JavaScript URL Parser Helper

// EXTENDED: https://gist.github.com/jlong/2428561

var url = {
	parse: function(urlString){
		var parser = document.createElement('a');
		parser.href = urlString;
		return parser;
	},
	append: function(urlString, key, value){
		var parser = this.parse(urlString),
			protocol = (parser.protocol.length) ? parser.protocol + '//' : '',
			hostname = (parser.host.length) ? parser.hostname : '',
			search = (parser.search.length) ? parser.search + '&' : '?';
		return protocol + hostname + parser.pathname + search + key + '=' + value + parser.hash;
	}
}

// Example: 
// var newUrl = url.append('http://www.example.com/product.html', 'foo', 'bar');