0

Possible Duplicate:
Get query string values in JavaScript

Say if,i've a URL like this update test

I want to check if URL has a parameter q.

Can i use $get() ,to do this.

If(urlparamerter == q)
{

   do some thing

}

Is there any jquery build in function which does this?

Thanks in advance!

Community
  • 1
  • 1

3 Answers3

3

No, there is no jQuery Built in function to do this. You can use the following function, found from this SO answer

function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}

To get the q parameter just call it like

var qvalue = getParameterByName('q');

UPDATE

If you want to use this function by passing url instead of using current page's url modify the function like follwoing

function getParameterByName(name,url) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(url);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}

and then you can call it like

var qvalue = getParameterByName('q','www.test.com?q=1')

Working Fiddle

Community
  • 1
  • 1
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
1

I would encourage you to check out the jQuery URL Parser plugin. It's a pretty straight-forward way of interacting with the url and queryString data:

var q = $.url().param("q"); // Gets the q parameter
Sampson
  • 265,109
  • 74
  • 539
  • 565
0

For GET parameters, you can grab them from document.location.search:

var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

document.write($_GET["test"]);

Or, here's a more generic version:

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

Or, better yet, grab them using PHP:

var $_GET = <?php echo json_encode($_GET); ?>;

This answer is from this thread.

Community
  • 1
  • 1
Norse
  • 5,674
  • 16
  • 50
  • 86