I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to de
If you are not interested in the host name (for example www.beta.example.com) but in the domain name (for example example.com), this works for valid host names:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
Try to run in script : path: http://localhost:4200/landing?query=1#2
console.log(window.location.hash)
Location have following values:
window.location.hash: "#2"
window.location.host: "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:"
window.location.search: "?query=1"
I'm new to JavaScript, but cant you just use: document.domain ?
Example:
<p id="ourdomain"></p>
<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>
Output:
domain.com
or
www.domain.com
Depending on what you use on your website.
You can get it from location object in Javascript easily:
For example URL of this page is:
http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc
Then we can get the exact domain with following properties of location object:
location.host = "www.stackoverflow.com"
location.protocol= "http:"
you can make the full domain with:
location.protocol + "//" + location.host
Which in this example returns http://www.stackoverflow.com
I addition of this we can get full URL and also the path with other properties of location object:
location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
If you want the country domain name - for example to extract .com from stackoverflow.com :
(ES6):
const getCountryDomainName = () => {
let hostName = window.location.hostname;
let lastDotIndex = hostName.lastIndexOf('.');
let countryDomainName = hostName.substr(lastDotIndex+1, hostName.length);
return countryDomainName;
}
(ES5):
function getCountryDomainName() {
let hostName = window.location.hostname;
let lastDotIndex = hostName.lastIndexOf('.');
let countryDomainName = hostName.substr(lastDotIndex+1, hostName.length);
return countryDomainName;
}
Then, just use the function to assign the value to a var:
const countryDomainName = getCountryDomainName();
How about:
window.location.hostname
The location object actually has a number of attributes referring to different parts of the URL