-2

I want to read an ID from a QueryString with jQuery; how can I do it in an efficient way?

Is there any way similar to $.QueryString?

Adriano
  • 3,363
  • 4
  • 32
  • 46
dnxit
  • 6,712
  • 2
  • 27
  • 33

3 Answers3

2

I use this, no extra library required:

//
// Given a parameter name, returns the corresponding querystring parameter.
//
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, " "));
}

Sample usage:

Id = parseInt(getParameterByName("id")) || 0;
E.J. Brennan
  • 43,955
  • 6
  • 83
  • 111
1

Assuming you are using jQuery - Querystring library

 var id = $.QueryString("paramter");  

Note: it will return null is the query string doesn't exist or the value of the query string if it exists

Satpal
  • 129,808
  • 12
  • 152
  • 166
0

Well I found this it might be helpful for someone

(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);

var id = $.QueryString["id"];
dnxit
  • 6,712
  • 2
  • 27
  • 33