Skip to content Skip to sidebar Skip to footer

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 corr

Solution 1:

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!

Solution 2:

If doing this in JavaScript, you don't even need a regex. You can use the location object like so:

var host = window.location.host;

This link has more information about how to get other parts of the URL: http://www.comptechdoc.org/independent/web/cgi/javamanual/javalocation.html.

Solution 3:

For full cross-browser compatibility simply go with the document object, not window:

var theHost = document.location.host;

Solution 4:

If you're really sold on using regular expressions rather than built-in tools in the language (e.g. PHP's parse_url function) then something like:

(?:(\w+)://)([^/]+)(/\w+)?

will do it in a very rough way, with the hostname in subgroup 2. This is just a quick-and-dirty hack though (and won't work in all cases), and I would advise using the language's built-in tools.

If it's Javascript and the current URL, look at window.location.host or window.location.hostname.

Post a Comment for "What's A Good Regular Expression To Capture The Root Domain Of A Given Url?"