Parsing URL hash/fragment identifier with JavaScri

2019-01-03 06:06发布

Looking for a way to parse key pairs out of the hash/fragment of a URL into an object/associative array with JavaScript/JQuery

9条回答
Rolldiameter
2楼-- · 2019-01-03 06:22

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;
}, {});
查看更多
该账号已被封号
3楼-- · 2019-01-03 06:24

You might want to check out jsuri. It seems to work well for me.

查看更多
Emotional °昔
4楼-- · 2019-01-03 06:28

You can also use the .hash property, demonstrated in this scrolling table of contents example for a clicked link or for the locatioin.

查看更多
贪生不怕死
5楼-- · 2019-01-03 06:33

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);
}, {});
查看更多
淡お忘
6楼-- · 2019-01-03 06:34

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-03 06:35

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'
});
查看更多
登录 后发表回答