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

前端 未结 22 1127
南方客
南方客 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('<br />');
    document.write('Hostname: ' + a.hostname);
    document.write('<br />');
    document.write('Pathname: ' + a.pathname);

    0 讨论(0)
  • 2020-11-21 23:28

    Stop reinventing the wheel. Use https://github.com/medialize/URI.js/

    var uri = new URI("http://example.org:80/foo/hello.html");
    // get host
    uri.host(); // returns string "example.org:80"
    // set host
    uri.host("example.org:80");
    
    0 讨论(0)
  • 2020-11-21 23:29
    function parseUrl(url) {
        var m = url.match(/^(([^:\/?#]+:)?(?:\/\/((?:([^\/?#:]*):([^\/?#:]*)@)?([^\/?#:]*)(?::([^\/?#:]*))?)))?([^?#]*)(\?[^#]*)?(#.*)?$/),
            r = {
                hash: m[10] || "",                   // #asd
                host: m[3] || "",                    // localhost:257
                hostname: m[6] || "",                // localhost
                href: m[0] || "",                    // http://username:password@localhost:257/deploy/?asd=asd#asd
                origin: m[1] || "",                  // http://username:password@localhost:257
                pathname: m[8] || (m[1] ? "/" : ""), // /deploy/
                port: m[7] || "",                    // 257
                protocol: m[2] || "",                // http:
                search: m[9] || "",                  // ?asd=asd
                username: m[4] || "",                // username
                password: m[5] || ""                 // password
            };
        if (r.protocol.length == 2) {
            r.protocol = "file:///" + r.protocol.toUpperCase();
            r.origin = r.protocol + "//" + r.host;
        }
        r.href = r.origin + r.pathname + r.search + r.hash;
        return r;
    };
    parseUrl("http://username:password@localhost:257/deploy/?asd=asd#asd");
    

    It works with both absolute and relative urls

    0 讨论(0)
  • 2020-11-21 23:30

    The AngularJS way - fiddle here: http://jsfiddle.net/PT5BG/4/

    <!DOCTYPE html>
    <html>
    <head>
        <title>Parse URL using AngularJS</title>
    </head>
    <body ng-app ng-controller="AppCtrl" ng-init="init()">
    
    <h3>Parse URL using AngularJS</h3>
    
    url: <input type="text" ng-model="url" value="" style="width:780px;">
    
    <ul>
        <li>href = {{parser.href}}</li>
        <li>protocol = {{parser.protocol}}</li>
        <li>host = {{parser.host}}</li>
        <li>hostname = {{parser.hostname}}</li>
        <li>port = {{parser.port}}</li>
        <li>pathname = {{parser.pathname}}</li>
        <li>hash = {{parser.hash}}</li>
        <li>search = {{parser.search}}</li>
    </ul>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    
    <script>
    function AppCtrl($scope) {
    
        $scope.$watch('url', function() {
            $scope.parser.href = $scope.url;
        });
    
        $scope.init = function() {
            $scope.parser = document.createElement('a');
            $scope.url = window.location;
        }
    
    }
    </script>
    
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题