How to retrieve the value of querystring from url using Javascript

Posted by ybbest on YBBest See other posts from YBBest or by ybbest
Published on Fri, 02 Mar 2012 08:29:52 +0000 Indexed on 2012/03/18 18:26 UTC
Read the original article Hit count: 262

Filed under:

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/


© YBBest or respective owner

Related posts about JavaScript