How do I parse a URL into hostname and path in javascript?
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
.
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"
found here: https://gist.github.com/jlong/2428561
var parser = document.createElement('a');parser.href = "http://example.com:3000/pathname/?search=test#hash";parser.protocol; // => "http:"parser.host; // => "example.com:3000"parser.hostname; // => "example.com"parser.port; // => "3000"parser.pathname; // => "/pathname/"parser.hash; // => "#hash"parser.search; // => "?search=test"parser.origin; // => "http://example.com:3000"