QueryString with javascript

JavaScript performance comparison

Revision 14 of this test case created

Info

Test two methods of retrieving QueryString values with javascript.

Preparation code

<script>
  var query = "q=my+search+query&value=55";
 
  window.GetQueryString = function(q) {
   return (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;
   })(q.split("&"));
  };
 
  window.getParameterByName = function(name) {
   name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
   var regexS = "[\\?&]" + name + "=([^&#]*)";
   var regex = new RegExp(regexS);
   var results = regex.exec(window.location.href);
   if (results == null) return "";
   else return decodeURIComponent(results[1].replace(/\+/g, " "));
  };

  window.createQueryStringParamsObject = function(q) {
    var urlParameters = {};
    var queryString = q;
    var paramName = "";
    var paramValue = "";
    var key = true;
    for (var i = 0; i < queryString .length; i++) {
        switch (queryString [i]) {
            case '=':
                key = false;
                break;

            case '&':
            case ';':
                urlParameters[decodeURIComponent(paramName)] = decodeURIComponent(paramValue);
                paramName = "";
                paramValue = "";
                key = true;
                break;

            default:
                if (key) {
                    paramName += queryString[i];
                }
                else {
                    paramValue += queryString[i];
                }
        }
    }
    if (paramName && !urlParameters.hasOwnProperty(paramName)) {
        urlParameters[paramName] = paramValue;
    }
    return urlParameters;
  };
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Split method
var qs = window.GetQueryString(query);

var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];
pending…
Regex method
var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");
pending…
Params Object
var params = window.createQueryStringParamsObject(query);

var search = params['q'];
var value = params['value'];
var undef = params['undefinedstring'];
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment