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

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

    What about simple regular expression?

    url = "http://www.example.com/path/to/somwhere";
    urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url);
    hostname = urlParts[1]; // www.example.com
    path = urlParts[2]; // /path/to/somwhere
    

提交回复
热议问题