[英]Parsing URL hash/fragment identifier with JavaScript
寻找一种使用 JavaScript/JQuery 将 URL 的散列/片段中的密钥对解析为对象/关联数组的方法
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不需要 JQuery/插件
Update:更新:
I'm now recommending the jQuery BBQ plugin as per Hovis's answer.我现在根据 Hovis 的回答推荐jQuery BBQ 插件。 It covers all hash parsing issues.它涵盖了所有哈希解析问题。
Update (2019)更新 (2019)
Apparently there is now a URLSearchParams function - see answer from @Berkant显然现在有一个 URLSearchParams 函数 - 请参阅@Berkant 的回答
Use URLSearchParams .使用URLSearchParams 。 Browser coverage: https://caniuse.com/urlsearchparams .浏览器覆盖范围: https : //caniuse.com/urlsearchparams 。 It's fully supported in major browsers.主要浏览器完全支持它。 Here is a polyfill if you need to use this on unsupported browsers.如果您需要在不受支持的浏览器上使用它,这里有一个 polyfill。
How to read a simple key:如何读取一个简单的密钥:
// window.location.hash = "#any_hash_key=any_value"
const parsedHash = new URLSearchParams(
window.location.hash.substr(1) // skip the first char (#)
);
console.log(parsedHash.get("any_hash_key")); // any_value
Check out the Mozilla docs I linked above to see all of the methods of the interface.查看我在上面链接的 Mozilla 文档以查看接口的所有方法。
Check out: jQuery BBQ退房: 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. jQuery BBQ 设计用于从 url(查询字符串或片段)解析事物,并进一步简化基于片段的历史记录。 This is the jQuery plugin Yarin was looking for before he put together a pure js solution.这是 Yarin 在组装纯 js 解决方案之前一直在寻找的 jQuery 插件。 Specifically, the deparam.fragment() function does the job.具体来说, deparam.fragment()函数可以完成这项工作。 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!) (我正在使用的支持站点使用异步搜索,并且因为 BBQ 使得将整个对象放入片段中变得微不足道,所以我使用它来“保留”我的搜索参数。这为我的用户提供了他们搜索的历史状态,以及允许他们为有用的搜索添加书签。最重要的是,当 QA 发现搜索缺陷时,他们可以直接链接到有问题的结果!)
Do this in pure Javascript:在纯 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'}
我正在使用jQuery URL 解析器库。
I was looking through a bunch of answers for this problem and wound up cobbling them together using one line with reduce
:我正在查看有关此问题的一堆答案,并最终使用带有reduce
一行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);
}, {});
This jquery API does parse hash tags: https://jhash.codeplex.com/这个jQuery API做解析哈希标签: 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'
});
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.