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.
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> ?
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.
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.
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, "" .
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With