如何在 Javascript 中解析 URL 查询参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8486099/
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-24 06:11:22  来源:igfitidea点击:

How do I parse a URL query parameters, in Javascript?

javascripturlquery-stringstring-parsing

提问by user847495

Possible Duplicate:
Use the get paramater of the url in javascript
How can I get query string values in JavaScript?

可能的重复:
在 javascript 中使用 url 的 get 参数
如何在 JavaScript 中获取查询字符串值?

In Javascript, how can I get the parameters of a URL string (not the current URL)?

在 Javascript 中,如何获取 URL 字符串(不是当前 URL)的参数?

like:

喜欢:

www.domain.com/?v=123&p=hello

Can I get "v" and "p" in a JSON object?

我可以在 JSON 对象中获得“v”和“p”吗?

回答by Jan Turoň

Today (2.5 years after this answer) you can safely useArray.forEach. As @ricosrealm suggests, decodeURIComponentwas used in this function.

今天(此答案后 2.5 年)您可以安全地使用Array.forEach. 正如@ricosrealm 所建议的,decodeURIComponent在这个函数中使用了。

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

其实没那么简单,看评论里的peer-review,特别是:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded =(@AndrewF)
  • non-encoded +(added by me)
  • 基于散列的路由(@cmfolio)
  • 数组参数(@user2368055)
  • 正确使用 decodeURIComponent 和非编码=(@AndrewF)
  • 非编码+(由我添加)

For further details, see MDN articleand RFC 3986.

有关更多详细信息,请参阅MDN 文章RFC 3986

Maybe this should go to codereview SE, but here is safer and regexp-free code:

也许这应该转到 codereview SE,但这里是更安全且无正则表达式的代码:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

这个函数甚至可以解析像这样的 URL

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

回答by James Allardice

You could get a JavaScript object containing the parameters with something like this:

你可以得到一个包含参数的 JavaScript 对象,如下所示:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =characters, and pairs themselves separated by &characters (or an =character for the first one). For your example, the above would result in:

正则表达式很可能会得到改进。它只是查找由=字符分隔的名称-值对,以及由&字符(或第一个=字符)分隔的对本身。对于您的示例,上述结果将导致:

{v: "123", p: "hello"}

{v: "123", p: "hello"}

Here's a working example.

这是一个工作示例

回答by codeAnand

var v = window.location.getParameter('v');
var p = window.location.getParameter('p');

now v and p are objects which have 123 and hello in them respectively

现在 v 和 p 是分别有 123 和 hello 的对象