Discussion on url analytic function encapsulation of js

  • 2021-07-01 06:22:27
  • OfStack

In actual development, when exchanging data with the background through get, the data needed is in url, so we need to obtain useful information in url. The functions encapsulated below can already analyze url thoroughly and can be used directly:


function parseURL(url) {
       var a = document.createElement('a');
    a.href = url;
    return {
      source: url,
      protocol: a.protocol.replace(':',''),
      host: a.hostname,
      port: a.port,
      query: a.search,
      params: (function(){
        var ret = {},
          seg = a.search.replace(/^\?/,'').split('&'),
          len = seg.length, i = 0, s; //len = 2
          alert(a.search)
        for (;i<len;i++) {
          if (!seg[i]) { continue; }
          s = seg[i].split('=');
          ret[s[0]] = s[1];
        }
        return ret;
      })(),
      file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
      hash: a.hash.replace('#',''),
      path: a.pathname.replace(/^([^\/])/,'/$1'),
      relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
      segments: a.pathname.replace(/^\//,'').split('/')
    };
  }

This function is used as follows:


var myURL = parseURL(window.location.href); // Pass parseURL Function to parse the url ; window.location.href Can be replaced with any to be resolved url If you write something else directly url The format should be a string; 
var search_obj = myURL.params;    // The parsing method is to set the search The content of is parsed into objects, which is convenient for data calling; Other methods can be tried by themselves; 
var url_post = myURL.post;    // The port number of the current page; 

Related articles: