PDA

View Full Version : a quick way to parse a URL in JavaScript


jasongr
06-08-2005, 11:54 AM
Hi People

Assuming I have the following JavaScript string:
var s ="a=1&b=2&c=3&d=4"

Is there a quick JavaScript function that will parse it and will return an array matching for each key its value?
i.e.
Array('a' => 1, 'b' => 2, 'c' =>3, 'd' => 4)

if not, what would be the easiest way to parse it?

regards

Jon Hanlon
06-08-2005, 07:15 PM
You use the split() method which splits a string into array members.
So here, we split on '&' and then on '='

Here is a function (getArgument) written to return a parameters value in the search string of the url:

function plusUnescape(str) { // the unescape function won't convert plus signs
str = '' + str; // to spaces; like you see in search strings
while (true) {
var i = str.indexOf('+');
if (i == -1) break;
str = str.substring(0,i) + ' ' + str.substring(i+1,str.length);
}
return unescape(str);
}

function getArgument (theKey) { // returns search argument or empty string
var args = new Array ();
var argstring = window.location.search;
if (argstring.charAt(0) != '?') return false;
argstring = argstring.substring(1, argstring.length);
var argarray = argstring.split('&');
for (var i=0; i < argarray.length; i++) {
var singlearg = argarray[i].split('=');
if (singlearg.length != 2) continue; // not a valid argument
var argsKey = plusUnescape(singlearg[0]);
var argsValue = plusUnescape(singlearg[1]);
args[argsKey] = argsValue;
}
var result = '';
if (typeof(args[('' + theKey)]) != "undefined")
result = args[('' + theKey)]
return result;
}


eg:
http://www.mysite.com?name=bozo&job=funny+clown

getArgument("name") = "bozo"
getArgument("job") = "funny clown"