Get URL Parameters Using Javascript
October 3, 2008
An easy way to parse the query string in your URL to grab certain values.
Get URL Parameters Using Javascript
Most of the server-side programming languages that I know of like PHP, ASP, or JSP give you easy access to parameters in the query string of a URL. Javascript does not give you easy access. With javascript you must write your own function to parse the window.location.href value to get the query string parameters you want. Here is a small function I wrote that will parse the window.location.href value and return the value for the parameter you specify. It does this using javascript’s built in regular expressions. Here is the function:
function gup( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; }
The way that the function is used is fairly simple. Let’s say you have the following URL:
http://www.foo.com/index.html?bob=123&frank=321&tom=213#top
You want to get the value from the frank parameter so you call the javascript function as follows:
var frank_param = gup( ‘frank’ );
Now if you look at the frank_param variable it contains the number 321. The query string was parsed by the regular expression and the value of the frank parameter was retrieved. The function is smart in a couple of ways. For example, if you have an anchor in your URL like our example URL above does (#top) the gup() function knows to stop before the # character. Also, if a requested parameter doesn’t exist in the query string then an empty string is returned instead of a null.
This function has worked very well for my query string parsing needs and should work well for you.
url source: http://www.netlobo.com/url_query_string_javascript.html

December 31, 2008 at 1:39 pm
hksbxflokpxrrswlwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch
January 6, 2009 at 9:35 pm
There is just a problem with encoded characters like space which become %20. Do you know if there is a method in javascript to decode this characters whithout making your own parser and be dependent of your server encoding (when url are generated on the server side). Thanks in advance.
February 13, 2009 at 5:31 pm
I havent think of that yet. Soon I’ll keep you posted.
March 5, 2009 at 4:25 pm
http://www.11tmr.com/11tmr.nsf/D6Plinks/MWHE-695L9Z
this one working fine
May 7, 2009 at 8:03 pm
it was gr8..helped me alot..thanks
saved from solving a jigsaw puzzle..
May 27, 2009 at 8:58 am
I still have to get my website on the web…