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

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

    Here's a simple function using a regexp that imitates the a tag behavior.

    Pros

    • predictable behaviour (no cross browser issues)
    • doesn't need the DOM
    • it's really short.

    Cons

    • The regexp is a bit difficult to read

    -

    function getLocation(href) {
        var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
        return match && {
            href: href,
            protocol: match[1],
            host: match[2],
            hostname: match[3],
            port: match[4],
            pathname: match[5],
            search: match[6],
            hash: match[7]
        }
    }
    

    -

    getLocation("http://example.com/");
    /*
    {
        "protocol": "http:",
        "host": "example.com",
        "hostname": "example.com",
        "port": undefined,
        "pathname": "/"
        "search": "",
        "hash": "",
    }
    */
    
    getLocation("http://example.com:3000/pathname/?search=test#hash");
    /*
    {
        "protocol": "http:",
        "host": "example.com:3000",
        "hostname": "example.com",
        "port": "3000",
        "pathname": "/pathname/",
        "search": "?search=test",
        "hash": "#hash"
    }
    */
    

    EDIT:

    Here's a breakdown of the regular expression

    var reURLInformation = new RegExp([
        '^(https?:)//', // protocol
        '(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
        '(/{0,1}[^?#]*)', // pathname
        '(\\?[^#]*|)', // search
        '(#.*|)$' // hash
    ].join(''));
    var match = href.match(reURLInformation);
    

提交回复
热议问题