Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: get and set URL hash parameters?

Tags:

javascript

How do you get and set URL hash parameters in pure JavaScript?

For example, I'd like to use parameters like this: myurl.com/#from=2012-01-05&to=2013-01-01

And I'd like to be able to get and set the from and to parameters in the above.

I'm happy to use the HTML5 history API if that's the best way of doing things.

like image 466
Richard Avatar asked May 16 '14 15:05

Richard


People also ask

How do I change the URL of a hash?

hash = '#food'; This will replace the URL's hash with the value you set for it. If you wish the change the hash within the URL when the user clicks an anchor tag, why not just use <a href="#bar">Foo</a> ?

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

How do I add a hash to a URL?

The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also. If the url does not contains a hash, then an empty string "" will be returned.

How do I find the URL hash?

Get hash value for the current URL Alternatively, if you need a hash value for the current window URL, you can just use window. location. hash , which returns a string containing a '#' , followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this returns an empty string, "" .


1 Answers

If you want to parse a hash URL:

var hash = window.location.hash.substr(1);  var result = hash.split('&').reduce(function (res, item) {     var parts = item.split('=');     res[parts[0]] = parts[1];     return res; }, {}); 

That way, if you have this: http://example.com/#from=2012-01-05&to=2013-01-01

It becomes: {'from': '2012-01-05', 'to':'2013-01-01'}

As @Dean Stamler notes in the comments, dont forget the empty starting object. }, {});

Now to set a hash URL:

window.location.hash = "from=2012-01-05&to=2013-01-01";

like image 109
crthompson Avatar answered Sep 20 '22 17:09

crthompson