Reputation: 34013
With the help from this answer I'm getting clean domain names from urls in strings, like the following:
url = "http://www.stackoverflow.com/questions/ask"
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
return matches ? matches[1] : url;
>> "www.stackoverflow.com"
I would like to remove the subdomain "www" (and the following dot) as well though, if existing. How would I change the above expression to accomplish this?
Upvotes: 1
Views: 1822
Reputation: 785098
You can match optional www.
after http://
:
var matches = url.match(/^https?\:\/\/(?:www\.)?([^\/?#]+)(?:[\/?#]|$)/i);
//=> ["http://www.stackoverflow.com/", "stackoverflow.com"]
Upvotes: 2
Reputation: 11671
You can try,
url = "http://www.stackoverflow.com/questions/ask"
var matches = url.match(/^https?\:\/\/(www\.)?([^\/?#]+)(?:[\/?#]|$)/i);
return matches ? matches[2] : url;
to support url addresses with and without www.
Upvotes: 0