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

IT技术 javascript url query-string string-parsing
2021-01-16 14:10:59

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

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

喜欢:

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

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

2个回答

今天(此答案后 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;
}

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

  • 基于散列的路由(@cmfolio)
  • 数组参数(@user2368055)
  • 正确使用 decodeURIComponent 和非编码=(@AndrewF)
  • 非编码+(由我添加)

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

也许这应该转到 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;
}

这个函数甚至可以解析像这样的 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
*/
参数名称和值都必须被解码。这是一个常见的错误。所以而不是result[item[0]] = decodeURIComponent(item[1]);它应该是:result[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
2021-03-19 14:10:59
每个项目都应该使用 decodeURIComponent() 进行 url 解码
2021-03-29 14:10:59
@GuillermoMoscoso 然后你会得到genre=R&B&name=John无法正确解析的字符串您需要在拆分字符串后进行解码并知道什么是键和什么是值,方括号作为“键中的键”需要特别注意,请参阅代码。
2021-04-02 14:10:59
另请注意,split("=")对于包含未编码 = 的参数值,使用将失败,这种情况不常见但肯定会发生。我建议使用正则表达式,以便在保持简洁的同时获得更好的逻辑。
2021-04-09 14:10:59
location.search不适用于基于散列的路由:http://localhost:9000/#/documents?lang=es将返回一个空字符串location.search您将不得不使用location.hashlocation.href代替。
2021-04-10 14:10:59

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

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

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

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

这是一个工作示例

为什么不使用window.location.getParameter?
2021-03-17 14:10:59
参数名称在技术上[^=#&]+不仅仅是[^=#]+- 没有值的名称是合法且常见的。还要确保名称和值都被解码:params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
2021-03-30 14:10:59
您的示例不返回对象(它返回 2 个字符串),并且它要求您事先知道参数的名称,考虑到 OP 试图执行的操作,不太可能是这种情况。另外,文档在getParameter哪里?
2021-04-09 14:10:59