js 获取url的多种方式

  1. window.location.href:这个属性返回当前窗口(当前页面、iframe)的完整 URL。
  2. window.parent.location.href 是上一层页面跳转url
  3. window.top.location.href 是最外层的页面跳转url
  4. document.URL:这个属性也可以用来获取当前窗口的完整 URL
  5. window.location.toString():使用该方法同样可以获得当前页面的完整 URL。
  6. window.location.protocol + '//' + window.location.host + window.location.pathname:通过拼接协议、主机和路径信息,我们也能够构建出完整的 URL 地址。
    console.log(window.location.protocol + '//' + window.location.host + window.location.pathname);
  7. 使用正则表达式提取: 如果你只需要从URL中提取特定部分,比如域名或查询参数等,你可以使用正则表达式配合match()方法进行匹配获取。例如:
    const url = window.top.location.href;
    const domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im)[1];
    console.log(domain); // 输出域名部分
    
    const params = {};
    url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
        params[key] = decodeURIComponent(value);
    });
    console.log(params); // 输出包含查询参数键值对组成的对象

猜你喜欢

转载自blog.csdn.net/qq_36657291/article/details/132555050