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

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

    var getLocation = function(href) {
        var l = document.createElement("a");
        l.href = href;
        return l;
    };
    var l = getLocation("http://example.com/path");
    console.debug(l.hostname)
    >> "example.com"
    console.debug(l.pathname)
    >> "/path"
    

提交回复
热议问题