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

前端 未结 22 1523
南方客
南方客 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: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;
    }

    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"
    }
    

提交回复
热议问题