views:

82

answers:

6

I have a url that looks like: http://www.my-site.com/#key=kj123asj. I would like to retrieve key using javascript.

Any help is appreciated.

A: 
var matches = location.href.match(/(key=)([a-z0-9]+)$/i);

The variable matches will be an array and matches[2] will contain the value of the key.

Robusto
+1  A: 

This JavaScript library can parse query strings in standard format that is to say:

http://www.my-site.com/?key=kj123asj

The code to get key would be:

var qs = new Querystring();
var key = qs.get("key");

http://adamv.com/dev/javascript/querystring

Adam
A: 

You can access the entire URL from the variable window.location.href. After that, it's just a matter of searching the string for the # or = character and extracting the data after it. For example:

var s = window.location.href;
var i = s.indexOf('=');
var value = s.substr(i+1);

Of course, that only gets you the first value, and only works if you only have one value you want to extract. However, you could have that one value a JSON-encoded object, like so:

http://www.somewebsite.com/#data={key: 1293, foo: "bar"}

Then, do:

var map = JSON.parse(value);

You can now use normal JavaScript techniques to access the items:

var key = map['key'] // 1293
var foo = map['foo'] // "bar"

That should get you started, at least.

crazy2be
+1  A: 
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');
Daok
+2  A: 
Kyle Jones