| Get URL Parameters Using Javascript |
|
An easy way to parse the query string in your URL to grab certain values. 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.jiawebdesign.com/dev/get-url-parameters.html?cp=testing The value of the variable cp is equal to testing in this example. This article source from here. |