Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good regular expression to capture the root domain of a given url?

Using javascript, how can I capture the string example.com from the current domain http://example.com/bar?param=value or https://www.example.com?

My first attempt doesn't work correctly:

https?://w?w?w?[.]?[^?/]
like image 618
Udbhav Avatar asked Dec 03 '22 06:12

Udbhav


1 Answers

You don't need regex for this! Let the browser parse it for you:

var a = document.createElement('a');
a.href = 'http://foo.com/bar?param=value';
a.hostname; // "foo.com"

Voila!

like image 199
Crescent Fresh Avatar answered May 25 '23 12:05

Crescent Fresh