如何在 Javascript 中解析 URL 查询参数?
可能的重复:
在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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
提出问题 2.5 年后您可以安全使用
Array.forEach。正如 @ricosrealm 所建议的,此函数中使用了
decodeURIComponent
。实际上没那么简单,请参阅评论中的同行评审,特别是:
=< 的正确使用/code> (@AndrewF)
+
(由我添加)有关更多详细信息,请参阅 MDN 文章 和 RFC 3986。
也许这应该去 codereview SE,但这里有更安全且无正则表达式的代码:
该函数甚至可以解析类似
问题提出 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.actually it's not that simple, see the peer-review in the comments, especially:
=
(@AndrewF)+
(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:
This function can parse even URLs like
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.
您可以获得一个包含如下参数的 JavaScript 对象:
正则表达式很可能会得到改进。它只是查找由
=
字符分隔的名称-值对,以及由&
字符分隔的名称/值对(或用于表示名称的=
字符)第一个)。对于您的示例,上面的结果将是:{v: "123", p: "hello"}
这是一个 工作示例。
You could get a JavaScript object containing the parameters with something like this:
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.