Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the host from a URL in JavaScript?

Tags:

Capture the domain till the ending characters $, \?, /, :. I need a regex that captures domian.com in all of these.

domain.com:3000
domain.com?pass=gas
domain.com/
domain.com
like image 227
ThomasReggi Avatar asked Nov 22 '12 05:11

ThomasReggi


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']').

How do I separate a path from URL?

To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string. Then we can use the pathname property to get the URL path. For instance, we write: const url = 'http://www.example.com/foo/path2/path3/path4'; const { pathname } = new URL(url); console.

How can we get hostname and port information in JavaScript?

If you only want to return the hostname value (excluding the port number), use the window. location. hostname method instead. This will return a string value containing the hostname and, if the port value is non-empty, a : symbol along with the port number of the URL.

How parse URL in HTML?

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.


1 Answers

If you actually have valid URLs, this will work:

var urls = [
    'http://domain.com:3000',
    'http://domain.com?pass=gas',
    'http://domain.com/',
    'http://domain.com'
];

for (x in urls) {
    var a = document.createElement('a');
    a.href = urls[x];
    console.log(a.hostname);
}

//=> domain.com
//=> domain.com
//=> domain.com
//=> domain.com

Note, using regex for this kind of thing is silly when the language you're using has other built-in methods.

Other properties available on A elements.

var a = document.createElement('a');
a.href = "http://domain.com:3000/path/to/something?query=string#fragment"

a.protocol   //=> http:
a.hostname   //=> domain.com
a.port       //=> 3000
a.pathname   //=> /path/to/something
a.search     //=> ?query=string
a.hash       //=> #fragment
a.host       //=> domain.com:3000

EDIT #2

Upon further consideration, I looked into the Node.js docs and found this little gem: url#parse

The code above can be rewritten as:

var url = require('url');

var urls = [
    'http://domain.com:3000',
    'http://domain.com?pass=gas',
    'http://domain.com/',
    'http://domain.com'
];

for (x in urls) {
    console.log(url.parse(urls[x]).hostname);
}

//=> domain.com
//=> domain.com
//=> domain.com
//=> domain.com

EDIT #1

See the revision history of this post if you'd like to see how to solve this problem using jsdom and nodejs

like image 147
maček Avatar answered Sep 22 '22 09:09

maček