js multiple ways to get url

  1. window.location.href: This property returns the complete URL of the current window (current page, iframe).
  2. window.parent.location.href is the previous page jump URL
  3. window.top.location.href is the outermost page jump url
  4. document.URL: This property can also be used to get the complete URL of the current window
  5. window.location.toString(): Use this method to also get the complete URL of the current page.
  6. window.location.protocol + '//' + window.location.host + window.location.pathname: By splicing protocol, host and path information, we can also construct a complete URL address.
    console.log(window.location.protocol + '//' + window.location.host + window.location.pathname);
  7. Use regular expression extraction: If you only need to extract specific parts from the URL, such as domain names or query parameters, you can use regular expressions with the match() method to obtain matches. For example:
    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); // 输出包含查询参数键值对组成的对象

Guess you like

Origin blog.csdn.net/qq_36657291/article/details/132555050