Wednesday, March 2, 2011
Get URL Parameters Using Javascript
Get URL Parameters Using Javascript
An easy way to parse the query string in your URL to grab certain values.
Source: http://www.netlobo.com/url_query_string_javascript.htmlexpressions. 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]; }
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.
Subscribe to:
Posts (Atom)