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

发布于 2024-12-20 20:14:05 字数 487 浏览 2 评论 0原文

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

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

例如:

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

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

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

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

like:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情何以堪。 2024-12-27 20:14:05

提出问题 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;
}

实际上没那么简单,请参阅评论中的同行评审,特别是:

  • 基于哈希的路由(@cmfolio)
  • 数组参数(@user2368055)
  • decodeURIComponent 和非编码 =< 的正确使用/code> (@AndrewF)
  • 非编码 + (由我添加)

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

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

function getSearchOrHashBased(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;
  return question==-1 || hash==question+1
    ? url.substring(hash)
    : url.substring(question+1, hash);
}

// use query = getSearchOrHashBased(location.href)
// or query = location.search.substring(1)
function getJsonFromUrl(query) {
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.replaceAll("+", " ");
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substring(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substring(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;
}

该函数甚至可以解析类似

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
*/

问题提出 7 年后的 URL,该功能被标准化为 URLSearchParams 4年后,访问可以通过 代理 进一步简化,如 < a href="https://stackoverflow.com/a/901144/343721">这个答案,但是这个新答案无法解析上面的示例网址。

2.5 years after the question was asked you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

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:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

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

function getSearchOrHashBased(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;
  return question==-1 || hash==question+1
    ? url.substring(hash)
    : url.substring(question+1, hash);
}

// use query = getSearchOrHashBased(location.href)
// or query = location.search.substring(1)
function getJsonFromUrl(query) {
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.replaceAll("+", " ");
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substring(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substring(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

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
*/

7 years after the question was asked the functionality was standardized as URLSearchParams and 4 more years after, the access can be further simplified by Proxy as explained in this answer, however that new one can not parse the sample url above.

安穩 2024-12-27 20:14:05

您可以获得一个包含如下参数的 JavaScript 对象:

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

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

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

这是一个 工作示例

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

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"}

Here's a working example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文