-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,788
  • 5
  • 32
  • 53
dnxit
  • 7,118
  • 2
  • 30
  • 34

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
  • 45,870
  • 7
  • 88
  • 116
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
  • 132,252
  • 13
  • 159
  • 168
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
  • 7,118
  • 2
  • 30
  • 34