Gsub string in javascript

I am trying to get only google.com domain name from javascript

 document.location.hostname 

This code returns www.google.com .

How can I get only google.com ? In this case, it would either remove www. , or get only the domain name (if there is such a method in javascript).

+4
source share
2 answers
 var host = location.hostname.replace( /www\./g, '' ); 

The 'g' flag is for 'global', which is necessary if you want to get a true "gsub" (all matches are replaced, not just the first ones).

It is better, however, to get the full TLD:

 var tld = location.hostname.replace( /^(.+\.)?(\w+\.\w+)$/, '$2' ); 

This will process domains like foo.bar.jim.jam.com and give you just jam.com .

+15
source

... I'm in chrome right now, and window.location.host does the trick.

EDIT

So, I'm an idiot ... BUT, I hope this will redeem:

Alternative to regex:

 var host = window.location.hostname.split('.') .filter( function(el, i, array){ return (i >= array.length - 2) } ) .join('.'); 
+1
source

All Articles