Query String with JavaScript

Query String are very common among web applications, i have used it very often with JSP and Servlets. I have not used query Strings with Java Script, This article describes it well.

Example Below –

— Java Script

In short use this function to grab the query string –

function getQuerystring(key, default_)
{
if (default_==null) default_=””;
key = key.replace(/[\[]/,”\\\[“).replace(/[\]]/,”\\\]”);
var regex = new RegExp(“[\\?&]”+key+”=([^&#]*)”);
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}

The getQuerystring function is simple to use. Let’s say you have the following URL:

http://www.bloggingdeveloper.com?author=bloggingdeveloper

and you want to get the “author” querystring’s value:

var author_value = getQuerystring(‘author’);

 

Escaping %20 ( for space) or %40 (for @ ) from query String

Lets take a look at the method getQuerystring again.  Here is the “step by step” explanation  of the method

key = key.replace(/[\[]/,”\\\[“).replace(/[\]]/,”\\\]”);
var regex = new RegExp(“[\\?&]”+key+”=([^&#]*)”);

The above lines prepares the regular expression that will be applied on the url gathered in the next line of code.

var qs = regex.exec(window.location.href);

Javascript location href property of DOM window object allows you to get or set the current URL. You can access the href property through location.href or window.location.href. Both methods will return the same result. If you are trying to assign the value retrieved from the Javascript location href to a variable or alert message box then it will return the current URL of the browser. And if you are trying to assign the value to the Javascript location href property then it will redirect the current URL to the specified location URL. more here

Some times though,you would want to escape the query string fillers and revert it back to original value ( ex : %20 to space ). If you want to achieve this, you need to add this line to the method which escapes the fillers and reverts the original query string values ( for example Java%20World to Java World )

var qs =  regex.exec( unescape(window.location.href) );

JSP

URl: http://myaddress.com/xyz?name=jill
String someName = request.getParameter(“name”) ;

 

Advertisements

Leave a comment

Filed under javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s