Home > javascript > How to retrieve the value of querystring from url using Javascript

How to retrieve the value of querystring from url using Javascript

The following is a Javascript function I found on the internet , I keep here just in case I need to use it again.

function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}

You can also add this method to jquery as below.

$.getParameterByName = function (name) {
            name = name.replace( /[\[]/ , "\\\[").replace( /[\]]/ , "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace( /\+/g , " "));
        };
        $(document).ready(function () {
            alert($.getParameterByName("id"));
        });

References:
http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript

http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

http://stackoverflow.com/questions/7541218/writing-jquery-static-util-methods

http://api.jquery.com/category/utilities/

Advertisements
Categories: javascript
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: