Extract hostname name from string

Chamilyan picture Chamilyan · Dec 14, 2011 · Viewed 260.6k times · Source

I would like to match just the root of a URL and not the whole URL from a text string. Given:

http://www.youtube.com/watch?v=ClkQA2Lb_iE
http://youtu.be/ClkQA2Lb_iE
http://www.example.com/12xy45
http://example.com/random

I want to get the 2 last instances resolving to the www.example.com or example.com domain.

I heard regex is slow and this would be my second regex expression on the page so If there is anyway to do it without regex let me know.

I'm seeking a JS/jQuery version of this solution.

Answer

Filip Roséen - refp picture Filip Roséen - refp · Dec 14, 2011

A neat trick without using regular expressions:

var tmp        = document.createElement ('a');
;   tmp.href   = "http://www.example.com/12xy45";

// tmp.hostname will now contain 'www.example.com'
// tmp.host will now contain hostname and port 'www.example.com:80'

Wrap the above in a function such as the below and you have yourself a superb way of snatching the domain part out of an URI.

function url_domain(data) {
  var    a      = document.createElement('a');
         a.href = data;
  return a.hostname;
}