JavaScript 可以访问当前 URL部分。 对于这个网址:
https://css-tricks.com/example/index.html?s=flexbox
- window.location.protocol = “http:”
- window.location.host = “css-tricks.com”
- window.location.pathname = “/example/index.html”
- window.location.search = “?s=flexbox”
因此,要在 JavaScript 中获取完整的 URL 路径:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search
如果您需要拆分路径名,例如像 https://css-tricks.com/blah/blah/blah/index.html 这样的 URL,您可以将字符串拆分为“/”字符
var pathArray = window.location.pathname.split('/');
然后通过数组的部分访问不同的部分,比如
var secondLevelLocation = pathArray[0];
要将路径名重新组合在一起,您可以将数组拼接在一起并将“/”重新放入:
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "/";
newPathname += pathArray[i];
}
可能要达到峰值的最快方法是将 window.location 放在 DevTools 控制台中,然后查看:

本文介绍了如何在JavaScript中访问和操作当前URL的各个部分,包括协议、主机、路径名和查询参数。通过示例展示了如何获取完整路径以及如何拆分和重组路径名。在开发者工具控制台中,可以快速检查`window.location`属性获取更多详细信息。

被折叠的 条评论
为什么被折叠?



