Almog
Almog

Reputation: 2837

Getting domain name from URL issue

I need some JavaScript help I have the following function

domain: function(){
var a = document.createElement('a');
a.href = this.url;
return a.hostname;
}

Which is great but when this.url is something like google.com (without the http or www) my return is localhost Any ideas?

Upvotes: 1

Views: 93

Answers (2)

user3883448
user3883448

Reputation:

To get the complete URL, use this,

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

Upvotes: 0

adeneo
adeneo

Reputation: 318162

You can add the protocol if it's missing, that way your URL will always be valid

domain: function(d){
    var a = document.createElement('a');
    a.href = this.url.match(/^[a-zA-Z]+:\/\//) ? this.url : 'http://' + this.url;
    return a.hostname;
}

FIDDLE

If the url passed is just google.com without a protocol, it's considered a relative URL, so the anchor ends up as

<a href="http://localhost/google.com"></a>

while if the URL is absolute and contains the protocol, it ends up as

<a href="http://google.com"></a>

That's why you have to prepend a protocol if it's missing.

Upvotes: 3

Related Questions