Discussion on JS's URL analytic function Encapsulation _javascript skill

Source: Internet
Author: User

In actual development, some of the data through the get way with the background, the need to use the data in the URL, so we need to obtain the URL useful information, the following encapsulated functions can be resolved to the URL is very thorough, you can take direct use of:

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 ('/')
    };
  

The use of this function is as follows:

var myurl = parseURL (window.location.href); Through the parseURL function to resolve the current page url;window.location.href can be replaced by any URL to parse, if you write the other URL directly, the format should be string;
var search_obj =  Myurl.params;  The Analytic method is to resolve the content of search to the object, to facilitate the call of data, and other methods can be tried by themselves;
var url_post = myurl.post; The port number of the current page;

The above is small series for everyone to talk about JS URL analytic function Package All content, I hope we support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.