Computer >> Computer tutorials >  >> Programming >> Javascript

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


The Window.location read-only property returns a Location object with information about the current location of the document. You can use this to parse the URL into the hostname and path.

The Location interface represents the location (URL) of the object it is linked to. Properties are available on location object −

Location.href − This is a DOMString containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document.

Location.protocol − The protocol scheme of the URL, including the final ':'.

Location.host − The host, that is the hostname, a ':', and the port of the URL.

Location.hostname − The domain of the URL.

Location.port − The port number of the URL.

Location.pathname − An initial '/' followed by the path of the URL.

Location.search − A '?' followed by the parameters or "querystring" of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring.

Location.hash − A '#' followed by the fragment identifier of the URL.

Location.username − The username specified before the domain name.

Location.password − The password specified before the domain name.

Example

Example Usage −

let hostname = location.hostname
let path = location.pathname
console.log(hostname)
console.log(path)

On the URL: https://www.tutorialspoint.com/ajax/index.htm

Output

This will give the output −

www.tutorialspoint.com
/ajax/index.htm