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

前端 未结 22 1124
南方客
南方客 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:03

    found here: https://gist.github.com/jlong/2428561

    var parser = document.createElement('a');
    parser.href = "http://example.com:3000/pathname/?search=test#hash";
    
    parser.protocol; // => "http:"
    parser.host;     // => "example.com:3000"
    parser.hostname; // => "example.com"
    parser.port;     // => "3000"
    parser.pathname; // => "/pathname/"
    parser.hash;     // => "#hash"
    parser.search;   // => "?search=test"
    parser.origin;   // => "http://example.com:3000"
    
    0 讨论(0)
  • 2020-11-21 23:05

    Just use url.js library (for web and node.js).

    https://github.com/websanova/js-url

    url: http://example.com?param=test#param=again
    
    url('?param'); // test
    url('#param'); // again
    url('protocol'); // http
    url('port'); // 80
    url('domain'); // example.com
    url('tld'); // com
    
    etc...
    
    0 讨论(0)
  • 2020-11-21 23:06

    Why do not use it?

            $scope.get_location=function(url_str){
            var parser = document.createElement('a');
            parser.href =url_str;//"http://example.com:3000/pathname/?search=test#hash";
            var info={
                protocol:parser.protocol,   
                hostname:parser.hostname, // => "example.com"
                port:parser.port,     // => "3000"
                pathname:parser.pathname, // => "/pathname/"
                search:parser.search,   // => "?search=test"
                hash:parser.hash,     // => "#hash"
                host:parser.host, // => "example.com:3000"      
            }
            return info;
        }
        alert( JSON.stringify( $scope.get_location("http://localhost:257/index.php/deploy/?asd=asd#asd"),null,4 ) );
    
    0 讨论(0)
  • 2020-11-21 23:12

    Here is a version that I copied from https://gist.github.com/1847816, but rewritten so it's easier to read and debug. The purpose of copying the of the anchor data to another variable named "result" is because the anchor data is pretty long, and so copying a limited number of values to the result will help simplify the result.

    /**
     * See: https://gist.github.com/1847816
     * Parse a URI, returning an object similar to Location
     * Usage: var uri = parseUri("hello?search#hash")
     */
    function parseUri(url) {
    
      var result = {};
    
      var anchor = document.createElement('a');
      anchor.href = url;
    
      var keys = 'protocol hostname host pathname port search hash href'.split(' ');
      for (var keyIndex in keys) {
        var currentKey = keys[keyIndex]; 
        result[currentKey] = anchor[currentKey];
      }
    
      result.toString = function() { return anchor.href; };
      result.requestUri = result.pathname + result.search;  
      return result;
    
    }
    
    0 讨论(0)
  • 2020-11-21 23:13

    Simple and robust solution using the module pattern. This includes a fix for IE where the pathname does not always have a leading forward-slash (/).

    I have created a Gist along with a JSFiddle which offers a more dynamic parser. I recommend you check it out and provide feedback.

    var URLParser = (function (document) {
        var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
        var self = function (url) {
            this.aEl = document.createElement('a');
            this.parse(url);
        };
        self.prototype.parse = function (url) {
            this.aEl.href = url;
            if (this.aEl.host == "") {
               this.aEl.href = this.aEl.href;
            }
            PROPS.forEach(function (prop) {
                switch (prop) {
                    case 'hash':
                        this[prop] = this.aEl[prop].substr(1);
                        break;
                    default:
                        this[prop] = this.aEl[prop];
                }
            }, this);
            if (this.pathname.indexOf('/') !== 0) {
                this.pathname = '/' + this.pathname;
            }
            this.requestUri = this.pathname + this.search;
        };
        self.prototype.toObj = function () {
            var obj = {};
            PROPS.forEach(function (prop) {
                obj[prop] = this[prop];
            }, this);
            obj.requestUri = this.requestUri;
            return obj;
        };
        self.prototype.toString = function () {
            return this.href;
        };
        return self;
    })(document);
    

    Demo

    var URLParser = (function(document) {
      var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
      var self = function(url) {
        this.aEl = document.createElement('a');
        this.parse(url);
      };
      self.prototype.parse = function(url) {
        this.aEl.href = url;
        if (this.aEl.host == "") {
          this.aEl.href = this.aEl.href;
        }
        PROPS.forEach(function(prop) {
          switch (prop) {
            case 'hash':
              this[prop] = this.aEl[prop].substr(1);
              break;
            default:
              this[prop] = this.aEl[prop];
          }
        }, this);
        if (this.pathname.indexOf('/') !== 0) {
          this.pathname = '/' + this.pathname;
        }
        this.requestUri = this.pathname + this.search;
      };
      self.prototype.toObj = function() {
        var obj = {};
        PROPS.forEach(function(prop) {
          obj[prop] = this[prop];
        }, this);
        obj.requestUri = this.requestUri;
        return obj;
      };
      self.prototype.toString = function() {
        return this.href;
      };
      return self;
    })(document);
    
    /* Main */
    var out = document.getElementById('out');
    var urls = [
      'https://www.example.org:5887/foo/bar?a=1&b=2#section-1',
      'ftp://www.files.com:22/folder?id=7'
    ];
    var parser = new URLParser();
    urls.forEach(function(url) {
      parser.parse(url);
      println(out, JSON.stringify(parser.toObj(), undefined, ' '), 0, '#0000A7');
    });
    
    /* Utility functions */
    function print(el, text, bgColor, fgColor) {
      var span = document.createElement('span');
      span.innerHTML = text;
      span.style['backgroundColor'] = bgColor || '#FFFFFF';
      span.style['color'] = fgColor || '#000000';
      el.appendChild(span);
    }
    function println(el, text, bgColor, fgColor) {
      print(el, text, bgColor, fgColor);
      el.appendChild(document.createElement('br'));
    }
    body {
      background: #444;
    }
    span {
      background-color: #fff;
      border: thin solid black;
      display: inline-block;
    }
    #out {
      display: block;
      font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
      font-size: 12px;
      white-space: pre;
    }
    <div id="out"></div>

    Output

    {
     "protocol": "https:",
     "hostname": "www.example.org",
     "host": "www.example.org:5887",
     "pathname": "/foo/bar",
     "port": "5887",
     "search": "?a=1&b=2",
     "hash": "section-1",
     "href": "https://www.example.org:5887/foo/bar?a=1&b=2#section-1",
     "requestUri": "/foo/bar?a=1&b=2"
    }
    {
     "protocol": "ftp:",
     "hostname": "www.files.com",
     "host": "www.files.com:22",
     "pathname": "/folder",
     "port": "22",
     "search": "?id=7",
     "hash": "",
     "href": "ftp://www.files.com:22/folder?id=7",
     "requestUri": "/folder?id=7"
    }
    
    0 讨论(0)
  • 2020-11-21 23:14

    For those looking for a modern solution that works in IE, Firefox, AND Chrome:

    None of these solutions that use a hyperlink element will work the same in chrome. If you pass an invalid (or blank) url to chrome, it will always return the host where the script is called from. So in IE you will get blank, whereas in Chrome you will get localhost (or whatever).

    If you are trying to look at the referrer, this is deceitful. You will want to make sure that the host you get back was in the original url to deal with this:

        function getHostNameFromUrl(url) {
            // <summary>Parses the domain/host from a given url.</summary>
            var a = document.createElement("a");
            a.href = url;
    
            // Handle chrome which will default to domain where script is called from if invalid
            return url.indexOf(a.hostname) != -1 ? a.hostname : '';
        }
    
    0 讨论(0)
提交回复
热议问题