Reputation: 2837
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
Reputation:
To get the complete URL, use this,
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
Upvotes: 0
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;
}
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