| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Friday, December 5, 2008

Parse URL Query String with Javascript

UPDATE!!! - I published a better, more elegant way to parse the query string here.

Here is a small bit of JavaScript to help you sort through a query string on a page. For example, say you want to use the variables sent to "State.aspx?s=Utah&id=5&person=Bob", this code will extract those variables and make them usable further down in the code:
<script type="text/javascript">
var aryV = location.search.replace("?","").split("&");
var i=0
while (i < aryV.length)
{ if (aryV[i].indexOf("s=") >= 0)
{ strState = aryV[i].substr(aryV[i].indexOf("=")+1).replace(/%20/g, " ");
strState = strState.replace(/\+/g, " ");
}
else if (aryV[i].indexOf("id=") >= 0)
{ strID = aryV[i].substr(aryV[i].indexOf("=")+1).replace(/%20/g, " ");
strID = strID.replace(/\+/g, " ");
}
else if (aryV[i].indexOf("person=") >= 0)
{ strPerson = aryV[i].substr(aryV[i].indexOf("=")+1).replace(/%20/g, " ");
strPerson = strPerson.replace(/\+/g, " ");
}
i+=1;
}

document.write("<tt>The State is : " + strState + "<br>");
document.write("The ID is : " + strID + "<br>");
document.write("The Person is: " + strPerson + "</tt>");
</script>

3 comments:

binnyva said...

I think a better way of doing this is to split using & and then using '=' - that way you will get an array of all the query items - you don't have to specify the names.

binnyva said...

A PoC code for the above comment...

http://pastebin.ca/1277528

Code needs the dump function to display the data.

And remember - I created it very quickly - expect bugs.

Ben said...

Hi Binny,

Thanks for taking the time to put that code together. I'm beginning to realize just how much about coding that I DON'T know.
I'll have to work with your code for a bit to really figure it out and understand it, there are some concepts and logic in it that I haven't worked with before.
Again, thanks!

-Ben