user948438237 user948438237 - 1 year ago 134
Javascript Question

Split and parse window.location.hash

I'm facing issues with splitting and parsing window.location.hash correctly.

First of all, we get few parameters in hash, ex:


As you surely see it's been created for search. When user clicks on pagination link page is being reloaded with the hash. So far so good.

I created function initialise() that is calling every time when there's hash in the URL:

if (window.location.hash) {
var params = (window.location.hash.substr(1)).split("&");

for (i = 0; i < params.length; i++)
var a = params[i].split("=");
// Now every parameter from the hash is beind handled this way
if (a[0] == "loc")

Everythig is almost working... When I choose all search params hash is being... cut. For unknown reason for me. I tried to use
if( params.indexOf('loc') )
instead of
a[0] == "loc"
without any luck.

Could you lend me a hand?


Of course, I was using var a = ... in the loop, it was only copy-paste error.

Answer Source

You don't need a loop, if it's only the value of loc from the hash you're after. This should also work.

var lochash    = location.hash.substr(1),
    mylocation = lochash.substr(lochash.indexOf('loc='))
if (mylocation) {

Concerning the trunctating of the hash after a page reload: imho that isn't related to your loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download