Question

Given an Url like this: http://mydomain.com/mypage.asp?Animal=Elephant

VBScript provides a nice way to get individual items in a QueryString using the Request object:

dim animal = Request.QueryString["Animal"]

I've seen some rather convoluted JavaScript floating around to do something similar, but I would hope that the jQuery library would have a function to do this without having to reinvent some wheel. I can't find it in the jQuery book I have, nor on the jQuery website.

Am I barking up the tree at nothing? Is there a NATIVE jQuery function to do this?

Please note that my question is asking for the existence of a NATIVE JQUERY FUNCTION to get a QueryString which is comparable to the VBScript I provided above. A ONE LINE SOLUTION to the question. Such as:

var animal = $.getParameterByName("Animal");

There are only 2 possible answers to my question. They are:

  1. No, there isn't a native one-line jQuery function as described, or
  2. Yes, there is a native one-line jQuery function as described, and here it is...

I know how to get the entire QueryString and how to parse it using Javascript - what I don't know is if there is a jQuery method or function that does what I ask.

Was it helpful?

Solution

"No, there isn't a native one-line jQuery function as described"

However, it's very easy to change that.

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

with that included in the head after jquery, you can now simply do:

var animal = $.getParameterByName("Animal");

Method for getting parameter by name taken from: How can I get query string values in JavaScript?

OTHER TIPS

I know this doesn't answer you question, but I agree that the VBScript way does feel nice.

window.Request = {
  QueryString: {}
};

window.location.search.split('?')[1].split('&').forEach(function(kv){
  Request.QueryString[kv.split('=')[0]] = decodeURIComponent(
    kv.split('=')[1].replace(/\+/g, " ")
  );
});

var animal = Request.QueryString['animal'];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top