I would like to take a string
var a = "http://example.com/aa/bb/"
and process it into an object such that
a.hostname == "example.com"
and
a.pathname == "/aa/bb"
The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').
The url. parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties.
Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use it for parsing the given URL. Method 2: In this method we will use URL() to create a new URL object and then use it for parsing the provided URL.
URL parsing is a function of traffic management and load-balancing products that scan URLs to determine how to forward traffic across different links or into different servers. A URL includes a protocol identifier (http, for Web traffic) and a resource name, such as www.microsoft.com.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With