如何使用JavaScript从当前URL获取查询字符串?

编程入门 行业动态 更新时间:2024-10-21 10:06:28
本文介绍了如何使用JavaScript从当前URL获取查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的网址:

localhost/PMApp/temp.htm?ProjectID=462

我需要做的是在之后获取详细信息? sign(查询字符串) - 即 ProjectID = 462 。我怎样才能使用JavaScript?

What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript?

到目前为止我所做的是:

var url = window.location.toString(); url.match(?);

我不知道下一步该做什么。

I don't know what to do next.

推荐答案

查看 MDN文章关于 window.location 。

QueryString在窗口中可用.location.search 。

The QueryString is available in window.location.search.

在旧版浏览器中也可以使用的解决方案

MDN提供了一个示例(在上面引用的文章中不再提供)如何获取QueryString中可用的单个键的get值。这样的事情:

MDN provide an example (no longer available in the above referenced article) of how to the get value of a single key available in the QueryString. Something like this:

function getQueryStringValue (key) { return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); } // Would write the value of the QueryString-variable called name to the console console.log(getQueryStringValue("name"));

在现代浏览器中

在现代浏览器中,您有 searchParams 属性,返回 URLSearchParams 对象。返回的对象有许多方便的方法,包括get-method。所以上面例子的等价物是:

In modern browsers you have the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams; let name = params.get("name");

URLSearchParams 接口也可用于解析查询字符串格式的字符串,并将它们转换为方便的URLSearchParams对象。

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337" let searchParams = new URLSearchParams(paramsString); searchParams.has("name") === true; // true searchParams.get("age") === "1337"; // true

请注意,此界面的浏览器支持仍然有限,所以如果你需要支持旧版浏览器,坚持使用第一个示例或使用 polyfill 。

更多推荐

如何使用JavaScript从当前URL获取查询字符串?

本文发布于:2023-11-17 12:07:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何使用   JavaScript   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!