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

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

    var loc = window.location;  // => "http://example.com:3000/pathname/?search=test#hash"
    

    returns the currentUrl.

    If you want to pass your own string as a url (doesn't work in IE11):

    var loc = new URL("http://example.com:3000/pathname/?search=test#hash")
    

    Then you can parse it like:

    loc.protocol; // => "http:"
    loc.host;     // => "example.com:3000"
    loc.hostname; // => "example.com"
    loc.port;     // => "3000"
    loc.pathname; // => "/pathname/"
    loc.hash;     // => "#hash"
    loc.search;   // => "?search=test"
    

提交回复
热议问题