views:

4826

answers:

6

Is there any JavaScript library that makes a dictionary out of the query string, ASP.NET style?

Something that would be used like:

var query = window.location.querystring["query"]?

Is a "query string" called something else outside the .NET realm? Why isn't location.search broken into a key/value collection already?

EDIT: I have written my own function, thanks, but does any major JavaScript library do this?

+16  A: 

You can extract the key/value pairs from the location.search property, this property has the part of the URL that follows the ? symbol, including the ? symbol.

function getQueryString() {
  var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

  while (m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }

  return result;
}

// ...
var myParam = getQueryString()["myParam"];
CMS
+1 This solution is full of win.
Iain Collins
This is not a win. What if a key's value has the '=' character in it? E.g. dork.com/?equation=10=2. You could argue it SHOULD be URL-encoded but it sure doesn't have to be. I made the mistake of writing a naive function like this myself once. There are more than one edge case this function account for.
JamesBrownIsDead
@James, forgot to mention that a couple of months ago I've modified the function, now it correctly can handle your example `dork.com/?equation=10=2` ...
CMS
A: 

Okay, since everyone is ignoring my actual question, heh, I'll post mine too! Here's what I have:

location.querystring = (function() {

    // The return is a collection of key/value pairs

    var queryStringDictionary = {};

    // Gets the query string, starts with '?'

    var querystring = unescape(location.search);

    // document.location.search is empty if no query string

    if (!querystring) {
        return {};
    }

    // Remove the '?' via substring(1)

    querystring = querystring.substring(1);

    // '&' seperates key/value pairs

    var pairs = querystring.split("&");

    // Load the key/values of the return collection

    for (var i = 0; i < pairs.length; i++) {
        var keyValuePair = pairs[i].split("=");
        queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
    }

    // Return the key/value pairs concatenated

    queryStringDictionary.toString = function() {

        if (queryStringDictionary.length == 0) {
            return "";
        }

        var toString = "?";

        for (var key in queryStringDictionary) {
            toString += key + "=" + queryStringDictionary[key];
        }

        return toString;
    };

    // Return the key/value dictionary

    return queryStringDictionary;
})();

And the tests:

alert(window.location.querystring.toString());

for (var key in location.querystring) {
    alert(key + "=" + location.querystring[key]);
}

Mind you thought, JavaScript isn't my native tongue.

Anyway, I'm looking for a JavaScript library (e.g. jQuery, Prototype) that already has one written. :)

Chris
I'm not convinced you really need a library to do what amounts to three lines of code above! Still, at least you would hope a library would remember the decodeURIComponent() both the key and value, something every code snippet posted so far has failed to do.
bobince
You don't need a library. I wanted to compare my implementation to one in a library so I could see if I was missing any edge cases. :)
Chris
A: 
Shadow2531
You can also .toLowerCase() the name if you want hfname matching to be case-insensitive.
Shadow2531
You can also check to see if the value is empty or not. If it is, you can skip adding the entry so the array only contains non-empty values.
Shadow2531
unescape() doesn't handle UTF-8 sequences, so you might want to use decodeURIComponent(). However then, if you want + chars to be decoded to spaces, run .replace(/\+/g, " ") on the string before decoding.
Shadow2531
+2  A: 

Maybe http://plugins.jquery.com/project/query-object?

Shadow2531
A: 

There are several js libraries out there, but this is the one I've used before: http://prettycode.org/2009/04/21/javascript-query-string/

Seems reasonable.

Squig
A: 

Try:

safalra.com/web-design/javascript/parsing-query-strings/

OR

adamv.com/dev/javascript/querystring

Since you wanted to compare your implementation to one in a library to see if there are any missing "edge cases", you can try plugging your URL into: http://urlparser.com/?url=Insert_URL

URLParser.com