How can I get query string values in JavaScript?

0 votes
80 views
asked Nov 28, 2013 in java script by anonymous

Hi

  Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how, and if not what plugin do you recommend?

2 Answers

0 votes
answered Nov 28, 2013 by simple

You don't need jQuery for that purpose. You can use pure JavaScript:

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, " "));
}
0 votes
answered Nov 28, 2013 by Bruno Lm

My method as a jQuery plugin

(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

Usage

$.QueryString["param"]
...