Looking for a way to parse key pairs out of the hash/fragment of a URL into an object/associative array with JavaScript/JQuery
-
You could probably do it with a pretty simple regexp. What "format" are the key/value pairs in the URL? – gnarf Nov 16 '10 at 18:59
-
Same as they would be in a query string- see my answer – Yarin Nov 16 '10 at 19:23
10 Answers
Here it is, modified from this query string parser:
function getHashParams() {
var hashParams = {};
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&;=]+)=?([^&;]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.hash.substring(1);
while (e = r.exec(q))
hashParams[d(e[1])] = d(e[2]);
return hashParams;
}
No JQuery/plug-in required
Update:
I'm now recommending the jQuery BBQ plugin as per Hovis's answer. It covers all hash parsing issues.
Update (2019)
Apparently there is now a URLSearchParams function - see answer from @Berkant

- 173,523
- 149
- 402
- 512
-
9could you elaborate on the "hash parsing issues"? I have the same need and I don't see anything wrong with your answer. – Christophe Oct 11 '12 at 21:03
-
@Christophe- I honestly can't recall. I'm sure my code works fine, but BBQ is a total plugin with hashchange events, query string parsing, etc, so probably that's what I meant.. – Yarin Sep 12 '13 at 16:31
-
2For basic handling your script is awesome!! Too often we default to jQuery libraries for basic tasks. Thanks! – SomethingOn Feb 07 '14 at 15:46
-
-
Jquery BBQ is no longer being updated and has issues with the latest JQuery. – crthompson Oct 19 '18 at 18:55
Use URLSearchParams. It's fully supported in major browsers and server-side JavaScript runtimes that implement WHATWG URL Standard. Browser coverage: https://caniuse.com/urlsearchparams.
Read a key from the current URL (assuming you are running on a browser UA):
// window.location.hash = "#any_hash_key=any_value"
const parsedHash = new URLSearchParams(
window.location.hash.substring(1) // any_hash_key=any_value
);
console.log(parsedHash.get("any_hash_key")); // any_value
Read a key from an arbitrary URL (make sure to check for exceptions that may be thrown by URL constructor when given URL is not valid):
const url = new URL("https://example.com#foo=bar&baz=qux&val=val+has+spaces");
const parsedHash = new URLSearchParams(
url.hash.substring(1) // foo=bar&baz=qux&val=val+has+spaces
);
console.log(parsedHash.get("baz")); // qux
console.log(parsedHash.get("val")); // val has spaces
Check out the Mozilla docs I linked above to see all of the methods of the interface.

- 707
- 7
- 12

- 1,077
- 12
- 20
-
1Agreed. Also, for multiple params, the format is as you would expect: a=foo&b=bar – Richard Nov 11 '19 at 05:35
-
2This should be the top answer, instead of all the ancient ones. Thanks! – Charming Robot May 31 '20 at 21:39
-
3Also, for anyone that wants the parsed hash as an object instead: `Object.fromEntries(parsedHash)` – worldsayshi Nov 29 '21 at 11:28
-
1I think substr can be replaced with slice , since substr became deprecated – Chakib Salah Apr 16 '22 at 01:03
-
This actually answers a different question, "how to parse hash in window.location". It doesn't answer the question how to parse a URL, while "ancient" ones do. – Fedor Losev Jul 05 '22 at 07:48
-
@FedorLosev it answers perfectly the OP question "Parsing URL hash/fragment identifier with JavaScript" – Zlatin Zlatev Dec 03 '22 at 18:34
-
@Zlatin Zlatev again, it answers how to parse window.location which is current page URL. URL isn't necessary the window.location. Perfect answer to OP question is a function that parses a given URL. How would you parse "http://google.com#s=123" with the given code? It just takes window.location.hash, so what does it answer... – Fedor Losev Feb 03 '23 at 01:49
-
Get the hash string from "google.com#s=123", which would be simple string operation, search and substring. See the first commented line which says ```// window.location.hash = "#any_hash_key=any_value"``` Basically replace window.location.hash with the hash string "s=123" which you have determined from the above string. @FedorLosev – Zlatin Zlatev Mar 24 '23 at 15:08
-
@FedorLosev how creating URLSearchParams object out of a string destroys my current hash? `var myHashURL = "https://google.com#s=123"; const parsedHash = new URLSearchParams(myHashURL.substring(myHashURL.indexOf('#')+1)); console.log(parsedHash.get("s"));` P.S. Surely if the interviewer is as arrogant as you and won't actually try to understand what I am saying, I won't even bother continuing the interview. – Zlatin Zlatev Mar 31 '23 at 23:02
-
@Zlatin Zlatev 1) The original answer did not contain the sample with URL etc., it only used window.locaiton.hash and originally did not answer the question, what are you arguing with by mentioning edited answer? Yes, now it looks legit after all the edits, that is true. But it wasn't, check the answer history 2) Your way with indexOf is still definitely a poor way for many reasons, use URL as in the edited answer. Why arrogant, really? Correct is correct, incorrect is incorrect, I'm not trying to make any point here, beyond that the previous stuff was not a good enough answer. Now it is. – Fedor Losev Jul 20 '23 at 01:19
Check out: jQuery BBQ
jQuery BBQ is designed for parsing things from the url (query string or fragment), and goes a bit farther to simplify fragment-based history. This is the jQuery plugin Yarin was looking for before he put together a pure js solution. Specifically, the deparam.fragment() function does the job. Have a look!
(The support site I'm working on uses an asynchronous search, and because BBQ makes it trivial to tuck entire objects into the fragment I use it to 'persist' my search parameters. This gives my users history states for their searches, and also allows them to bookmark useful searches. Best of all, when QA finds a search defect they can link straight to the problematic results!)

- 173,523
- 149
- 402
- 512

- 879
- 9
- 14
-
@Hovis- this is indeed an awesome plugin, and in fact I've switched over to using it as well. Giving you the answer as it's a much better option than my scratch function. – Yarin Nov 30 '11 at 21:35
-
-
7BBQ doesn't work well with Jquery 1.9+ and throws exceptions on load. It hasn't been updated in over three years. I'm not sure BBQ is still a good recommendation. You may be able to hack it to get it to work, see this: https://github.com/cowboy/jquery-bbq/pull/41 – nostromo Oct 21 '13 at 07:05
Do this in pure Javascript:
var hash = window.location.hash.substr(1);
var result = hash.split('&').reduce(function (result, item) {
var parts = item.split('=');
result[parts[0]] = parts[1];
return result;
}, {});
http://example.com/#from=2012-01-05&to=2013-01-01
becomes
{from: '2012-01-05', to:'2013-01-01'}

- 15,653
- 6
- 58
- 80
-
This does not handle decoding, for example `#this=is+a+test` the plus signs should be convert to spaces... and there are a dozen other special cases. It is crazy to try to implement this yourself. It is such a common problem. – John Henckel Aug 19 '20 at 18:52
-
2i retract the 'crazy to try...' comment! trying to implement something is a great way to learn. Despite being 3 yrs old, this is still a common question, and downvoting is how we curate the knowledge. At the moment your answer is rated *higher* than the one about `URLSearchParams` which is the issue i was trying to fix by downvoting. – John Henckel Aug 20 '20 at 13:30
-
@JohnHenckel, if you need url decoding, just add a line to do url decoding. The reason why this has been such a popular answer is that it doesnt use other libraries. Also, its had several years to get to this level. Given time, the others will to. No need to be petty, upvote what you like, let others do the same. ;) – crthompson Mar 27 '22 at 16:39
-
I would still urge the people to try using approach with `URLSearchParams` described in https://stackoverflow.com/a/57018898/481422 as using browser native implementations for certain functionalities at least in theory should be faster than any logic you create with javascript. – Zlatin Zlatev Dec 03 '22 at 18:37
-
@ZlatinZlatev the way you do that is by upvoting. Your suggestion is the second highest voted answer on the page, i'm sure people are already urged because of that. this just offers a different alternative. – crthompson Dec 13 '22 at 21:02
I am using jQuery URL Parser library.

- 109,619
- 77
- 317
- 330
-
2This parses the url itself -- not the hash items. Useful, but not what the original question is about. – Dan Esparza Dec 15 '10 at 18:30
I was looking through a bunch of answers for this problem and wound up cobbling them together using one line with reduce
:
const hashObj = location.hash.replace('#', '').split('&').reduce((prev, item) => Object.assign({[item.split('=')[0]]: item.split('=')[1]}, prev), {});
There's obviously a lot going on in that one line. It can be rewritten like this for clariry:
const hashObj = location.hash.replace('#', '').split('&').reduce((prev, item) => {
return Object.assign({[item.split('=')[0]]: item.split('=')[1]}, prev);
}, {});

- 983
- 7
- 16
You can also use the .hash property, demonstrated in this scrolling table of contents example for a clicked link or for the locatioin.
This jquery API does parse hash tags: https://jhash.codeplex.com/
// get the "name" querystring value
var n = jHash.val('name');
// get the "location" querystring value
var l = jHash.val('location');
// set some querystring values
jHash.val({
name: 'Chris',
location: 'WI'
});

- 486
- 1
- 6
- 22
My answer to this question should do what you're looking for:
url_args_decode = function (url) {
var args_enc, el, i, nameval, ret;
ret = {};
// use the DOM to parse the URL via an 'a' element
el = document.createElement("a");
el.href = url;
// strip off initial ? on search and split
args_enc = el.search.substring(1).split('&');
for (i = 0; i < args_enc.length; i++) {
// convert + into space, split on =, and then decode
args_enc[i].replace(/\+/g, ' ');
nameval = args_enc[i].split('=', 2);
ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
}
return ret;
};