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).
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
Javascript strings are immutable, they cannot be modified "in place" so you cannot modify a single character. in fact every occurence of the same string is ONE object.
The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.
replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.
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
.
... I'm in chrome right now, and window.location.host
does the trick.
EDIT
So I'm an idiot... BUT hopefully this will redeem:
An alternate to regex:
var host = window.location.hostname.split('.')
.filter(
function(el, i, array){
return (i >= array.length - 2)
}
)
.join('.');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With