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

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

    The modern way:

    new URL("http://example.com/aa/bb/")
    

    Returns an object with properties hostname and pathname, along with a few others.

    The first argument is a relative or absolute URL; if it's relative, then you need to specify the second argument (the base URL). For example, for a URL relative to the current page:

    new URL("/aa/bb/", location)
    

    In addition to browsers, this API is also available in Node.js since v7, through require('url').URL.

提交回复
热议问题