3

I want to parse the hash fragment into an associative array in javascript, just like the $_GET superglobal in PHP. Here is the URL:

www.mysite.com/randompage#name=donald&lastname=mclotsoquestions&age=25

So far I have this:

var hashfragment = location.hash;
var hashfragment_array = hashfragment.split('&');

Hashfragment_array is ["#name=donald","lastname=mclotsoquestions","age=25"]

How can I create key value pairs from this?

Don P
  • 60,113
  • 114
  • 300
  • 432

3 Answers3

5

Use this:

var hash_array = location.hash.substring(1).split('&');
var hash_key_val = new Array(hash_array.length);

for (var i = 0; i < hash_array.length; i++) {
    hash_key_val[i] = hash_array[i].split('=');
}

Now hash_key_val[index] is a two element array, where first element is a key - parameter name, and the second is it's corresponding value.

Edit:

After a while of studying this case I felt I need to rewrite this - return an object instead of array of arrays. I see balafi have done it before, but I can't bear my answer being so counterintuitive and bloatin' usage. Full example in the fiddle. Function source here:

function getParameters(location) {
    if (typeof location === 'undefined') {
        location = window.location;
    }
    var hashParams = new (function Params() {})();
    if (location.hash.length === 0) {
        return hashParams;
    };
    var hashArray = location.hash.substring(1).split('&');
    for (var i in hashArray) {
        var keyValPair = hashArray[i].split('=');
        hashParams[keyValPair[0]] = keyValPair[1];
    }
    return hashParams;
}
Krzysztof Jabłoński
  • 1,890
  • 1
  • 20
  • 29
  • 1
    I'm not sure I understand your answer. hash_key_val will only give the last key value pair in the hash_array. In the above example, it only returns 'age' and '25'. How would you get the value for 'name'? – Don P Sep 22 '12 at 18:11
  • 1
    `console.log(hash_key_val)` gives ['age', '25'] but none of the other key value pairs – Don P Sep 22 '12 at 18:13
  • Thanks @DonnyP. There was an error in my code. I was assigning to whole `hash_key_val` instead of assigning to it's element. That's why only the last sustained. I've corrected that. [Here](http://jsfiddle.net/MBFuE/) it works as intended. Thanks for drawing my attention. – Krzysztof Jabłoński Sep 23 '12 at 08:46
4
var str = www.mysite.com/randompage#name=donald&lastname=mclotsoquestions&age=25

var vars = str.substring(1).split('&');
var key = {};
for (i=0; i<vars.length; i++) {
  var tmp = vars[i].split('=');
  key[tmp[0]] = tmp[1];
} 

// key['name'] = "donald"  <--
// key['lastname'] = "mclotsoquestions"  <--
// key['age'] = "25"  <--
balafi
  • 2,143
  • 3
  • 17
  • 20
3

Use jQuery BBQ, which is a battle-tested library that handles state management.

$(window).on('hashchange', function(e) { // event fired when the fragment changes
    var frag = $.deparam.fragment();
});

It also makes adding or changing the fragment easy:

$.bbq.pushState({ someParam: 'value' });
josh3736
  • 139,160
  • 33
  • 216
  • 263
  • bbq no longer works with jQuery (1.9+) -- it looks like it hasn't been updated in several years. – nostromo Nov 12 '13 at 18:36
  • 1
    @nostromo: That's because jQuery 1.9 removed `$.browser`. There's [a BBQ PR that fixes the issue](https://github.com/cowboy/jquery-bbq/pull/41). The [project status is discussed here](https://github.com/cowboy/jquery-bbq/issues/49) -- it's not quite dead. – josh3736 Nov 12 '13 at 18:44