Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  3] [ 2]  / answers: 1 / hits: 17045  / 12 Years ago, sat, december 22, 2012, 12:00:00

I try to get only the domain name i.e. google.com from javascript



document.location.hostname


This code returns www.google.com.



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


More From » javascript

 Answers
31
var host = location.hostname.replace( /www./g, '' );


The 'g' flag is for 'global', which is needed if you want a true gsub (all matches replaced, not just the first).



Better, though, would be to get the full TLD:



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


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


[#81274] Thursday, December 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 3 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;