使用 JavaScript 解析 URL 哈希/片段标识符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4197591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:20:18  来源:igfitidea点击:

Parsing URL hash/fragment identifier with JavaScript

javascriptjqueryurlhashfragment-identifier

提问by Yarin

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

寻找一种使用 JavaScript/JQuery 将 URL 的哈希/片段中的密钥对解析为对象/关联数组的方法

采纳答案by Hovis Biddle

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. 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!

jQuery BBQ 旨在从 url(查询字符串或片段)解析事物,并进一步简化基于片段的历史记录。这是 Yarin 在构建纯 js 解决方案之前一直在寻找的 jQuery 插件。具体来说,deparam.fragment()函数可以完成这项工作。看一看!

(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 发现搜索缺陷时,他们可以直接链接到有问题的结果!)

回答by Yarin

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 pluginas per Hovis's answer. It covers all hash parsing issues.

我现在根据 Hovis 的回答推荐jQuery BBQ 插件。它涵盖了所有哈希解析问题。

Update (2019)

更新 (2019)

Apparently there is now a URLSearchParams function - see answerfrom @Berkant

显然现在有一个 URLSearchParams 函数 - 请参阅@Berkant 的回答

回答by paqogomez

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

http://example.com/#from=2012-01-05&to=2013-01-01

becomes

变成

{from: '2012-01-05', to:'2013-01-01'}

{from: '2012-01-05', to:'2013-01-01'}

回答by Berkant

Use URLSearchParams. Browser coverage: https://caniuse.com/#search=URLSearchParams. It's fully supported in major browsers. Hereis a polyfill if you need to use this on unsupported browsers.

使用URLSearchParams。浏览器覆盖范围:https: //caniuse.com/#search=URLSearchParams。主要浏览器完全支持它。如果您需要在不受支持的浏览器上使用它,这里有一个 polyfill。

How to read a simple key:

如何读取一个简单的密钥:

// window.location.hash = "#any_hash_key=any_value"

var 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 文档以查看接口的所有方法。

回答by serg

I am using jQuery URL Parserlibrary.

我正在使用jQuery URL 解析器库。

回答by mccambridge

I was looking through a bunch of answers for this problem and wound up cobbling them together using one line with 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);
}, {});

回答by yuvilio

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

您还可以使用 .hash 属性,在此滚动目录示例中演示用于单击的链接或locatioin

回答by SomeoneElse

This jquery API doesparse 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'
});

回答by BMitch

My answer to this questionshould 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;
};

回答by gatoatigrado

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

您可能想查看jsuri。这对我来说似乎很有效。