Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

url

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" 
like image 704
freddiefujiwara Avatar asked Apr 10 '09 02:04

freddiefujiwara


People also ask

How do I find the hostname of a URL?

The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').

Which method can you used to parse an address with the URL?

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.

How do you parse a link?

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.

What is parsing a 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.


1 Answers

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.

like image 103
rvighne Avatar answered Sep 22 '22 02:09

rvighne