获取当前页面的url

  获取当前页面的url,可以使用window.location.href

  如果想进一步获取到主机名,端口号等可以直接使用

  window.location.host //主机名加端口号

  window.location.hostname  //主机名

  window.location.origin   //协议主机名端口号

  window.location.pathname  //路径名

  window.location.port   //端口号

  window.location.protocol  //协议名

  window.location.hash  //描点  #后面的内容

  注意,当window.location = url  和 window.location.href = url  具有相同的功能。

  但是window.location返回的是一个对象,可以像上面那样调用相应的属性。

  而 window.location.href返回的是一个字符串。

  

  另外一思路是获取到地址字符串后,用正则来匹配,得到想要的信息。

  还有一种做法

  var test = document.createElement('a');

  test.href = window.location.href;

  test.search //得到查询部分,?以后的内容

  test.host  //得到主机名

  用法和上面的window.location一样,但是test并不等于同于document.location;

  

原文地址:https://www.cnblogs.com/sujianfeng/p/8692231.html