在 JavaScript 中获取 URL 和 URL 部分

Avatar of Chris Coyier
Chris Coyier

JavaScript 可以分段访问当前 URL。对于此 URL

https://css-tricks.org.cn/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

处理 URL 的一种更现代的方法是 URL() 全局方法

例如,如果您需要分解路径名,例如 URL https://css-tricks.org.cn/blah/blah/blah/index.html,您可以根据“/”字符分割字符串

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 控制台中并查看