Consider the following code:
hashString = window.location.hash.substring(1);
alert('Hash String = '+hashString);
When run with the following hash:
#car=Town%20%26%20Country
the result in Chrome and Safari will be:
car=Town%20%26%20Country
but in Firefox (Mac AND PC) will be:
car=Town & Country
Because I use the same code to parse query and hash params:
function parseParams(paramString) {
var params = {};
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&;=]+)=?([^&;]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = paramString;
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
Firefox's idiosyncrasy here breaks it: The car param winds up being "Town", no country.
Is there a safe way to parse hash params across browsers, or to fix how Firefox reads them?
NOTE: This issue is limited to Firefox's parsing of HASH params. When running the same test with query strings:
queryString = window.location.search.substring(1);
alert('Query String = '+queryString);
all browsers will show:
car=Town%20%26%20Country
The window. location. hash returns a string that contains a # along with the fragment identifier of the URL. The fragment identifier of the URL starts with a # followed by an identifier that uniquely identifies a section in an HTML document.
The Location Hash property in HTML is used to return the anchor part of a URL. It can also be used to set the anchor part of the URL. It returns the string which represents the anchor part of a URL including the hash '#' sign.
window.location.pathname returns the path and filename of the current page. window.location.protocol returns the web protocol used (http: or https:) window.location.assign() loads a new document.
In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier.
A workaround is to use
window.location.toString().split('#')[1] // car=Town%20%26%20Country
Instead of
window.location.hash.substring(1);
May I also suggest a different method (looks simpler to understand IMHO)
function getHashParams() {
// Also remove the query string
var hash = window.location.toString().split(/[#?]/)[1];
var parts = hash.split(/[=&]/);
var hashObject = {};
for (var i = 0; i < parts.length; i+=2) {
hashObject[decodeURIComponent(parts[i])] = decodeURIComponent(parts[i+1]);
}
return hashObject;
}
Test Case
url = http://stackoverflow.com/questions/7338373/window-location-hash-issue-in-firefox#car%20type=Town%20%26%20Country&car color=red?qs1=two&qs2=anything
getHashParams() // returns {"car type": "Town & Country", "car color": "red"}
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