Parsing The URL In JavaScript

When I need to parse the URL in JavaScript I use one of the following chunks of code. The first one is what I use when I need to just extract a single parameter. The second one returns a hash of all the parameters. That is faster when I need more than one parameter.


function getURLString(name,s) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(s)||[,""])[1].replace(/\+/g, '%20'))||"";
}




For a query of a=12&b=22 and a call of getURLString('b','a=12&b=22') you get "22" returned.



	function URLStrToHash(query) {
		var rv = {};
		var decode = function (s) { return decodeURIComponent(s.replace(/^\?/,"").replace(/\+/g, " ")); };

		var p1 = query.replace(/([^&=]+)=?([^&]*)/g,function(j,n,v){
			n = decode(n);
			v = decode(v);
			if ( typeof(rv[n]) === "undefined" ) {
				rv[n] = ( typeof v === "undefined" ) ? "" : v;
			} else if ( typeof(rv[n]) === "string" ) {
				var x = rv[n];
				rv[n] = [];
				rv[n].push ( x );
				rv[n].push ( v );
			} else {
				rv[n].push ( v );
			}
			return "";
		});
		return rv;
	}


var v = URLStrToHash("a=12&b=22&c&d");
console.log ( 'v=', v );
var v = URLStrToHash("a=12&b=22&x=aa&x=bb&x=cc&x=dd&x=ee&d=888888");
console.log ( 'v=', v );







For a query of, a=12&b=22&c&d it will return a hash of

{ a: '12', b: '22', c: '', d: '' }


This takes care of empty values by giving them an empty string.

For a query of, a=12&b=22&x=aa&x=bb&x=cc&x=dd&x=ee&d=888888 it will return a hash of

{
  a: '12',
  b: '22',
  x: [ 'aa', 'bb', 'cc', 'dd', 'ee' ],
  d: '888888'
}

Values specified more than once are returned in an array of values.


•       •       •       •       •       •

Summary: # of Words: 219
Author: Philip Schlump
Published On: 2013-05-05

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens