How do I parse a URL into hostname and path in javascript?

前端 未结 22 1516
南方客
南方客 2020-11-21 22:38

I would like to take a string

var a = \"http://example.com/aa/bb/\"

and process it into an object such that

a.hostname == \         


        
22条回答
  •  余生分开走
    2020-11-21 23:26

    freddiefujiwara's answer is pretty good but I also needed to support relative URLs within Internet Explorer. I came up with the following solution:

    function getLocation(href) {
        var location = document.createElement("a");
        location.href = href;
        // IE doesn't populate all link properties when setting .href with a relative URL,
        // however .href will return an absolute URL which then can be used on itself
        // to populate these additional fields.
        if (location.host == "") {
          location.href = location.href;
        }
        return location;
    };
    

    Now use it to get the needed properties:

    var a = getLocation('http://example.com/aa/bb/');
    document.write(a.hostname);
    document.write(a.pathname);
    

    Example:

    function getLocation(href) {
      var location = document.createElement("a");
      location.href = href;
      // IE doesn't populate all link properties when setting .href with a relative URL,
      // however .href will return an absolute URL which then can be used on itself
      // to populate these additional fields.
      if (location.host == "") {
        location.href = location.href;
      }
      return location;
    };
    var urlToParse = 'http://example.com/aa/bb/',
      a = getLocation(urlToParse);
    document.write('Absolute URL: ' + urlToParse);
    document.write('
    '); document.write('Hostname: ' + a.hostname); document.write('
    '); document.write('Pathname: ' + a.pathname);

提交回复
热议问题