如何在Javascript中解析URL查询参数?(复制)

时间:2021-04-30 23:59:02

Possible Duplicate:
Use the get paramater of the url in javascript
Get query string values in JavaScript

可能的复制:在javascript中使用url的get paramater获取查询字符串值。

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吗?

3 个解决方案

#1


74  

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

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

function getJsonFromUrl() {
  var query = location.search.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:

实际上并不是那么简单,请在评论中看到同行评议,特别是:

  • hash based routing (@cmfolio)
  • 基于哈希的路由(@cmfolio)
  • array parameters (@user2368055)
  • 数组参数(@user2368055)
  • proper use of decodeURIComponent (@AndrewF)
  • 正确使用decodeURIComponent (@AndrewF)

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

也许这应该去codereview SE,但这里有更安全的和regexpfree代码:

function getJsonFromUrl(hashBased) {
  var query;
  if(hashBased) {
    var pos = location.href.indexOf("?");
    if(pos==-1) return [];
    query = location.href.substr(pos+1);
  } else {
    query = location.search.substr(1);
  }
  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;
}

I also replaced non-encoded + for space according to this article which is also useful guide how to encode adhering to RFC 3986.

我还根据这篇文章替换了非编码的+空间,这也是如何编码遵循RFC 3986的有用指南。

Note the result[key][index] = val: a new array item is created, it is enumerable, so it can be iterated by forEach call. Therefore, you can parse even URLs like

注意结果[key][index] = val:创建了一个新的数组项,它是可枚举的,因此可以通过forEach调用迭代它。因此,您甚至可以解析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
*/

#2


19  

You could get a JavaScript object (a map) of 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"}

p { v:" 123 ":"你好" }

Here's a working example.

这是一个工作示例。

#3


-19  

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的对象。

#1


74  

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

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

function getJsonFromUrl() {
  var query = location.search.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:

实际上并不是那么简单,请在评论中看到同行评议,特别是:

  • hash based routing (@cmfolio)
  • 基于哈希的路由(@cmfolio)
  • array parameters (@user2368055)
  • 数组参数(@user2368055)
  • proper use of decodeURIComponent (@AndrewF)
  • 正确使用decodeURIComponent (@AndrewF)

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

也许这应该去codereview SE,但这里有更安全的和regexpfree代码:

function getJsonFromUrl(hashBased) {
  var query;
  if(hashBased) {
    var pos = location.href.indexOf("?");
    if(pos==-1) return [];
    query = location.href.substr(pos+1);
  } else {
    query = location.search.substr(1);
  }
  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;
}

I also replaced non-encoded + for space according to this article which is also useful guide how to encode adhering to RFC 3986.

我还根据这篇文章替换了非编码的+空间,这也是如何编码遵循RFC 3986的有用指南。

Note the result[key][index] = val: a new array item is created, it is enumerable, so it can be iterated by forEach call. Therefore, you can parse even URLs like

注意结果[key][index] = val:创建了一个新的数组项,它是可枚举的,因此可以通过forEach调用迭代它。因此,您甚至可以解析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
*/

#2


19  

You could get a JavaScript object (a map) of 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"}

p { v:" 123 ":"你好" }

Here's a working example.

这是一个工作示例。

#3


-19  

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的对象。