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

前端 未结 22 1527
南方客
南方客 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条回答
  •  萌比男神i
    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;
    
    }
    

提交回复
热议问题