How i can get the domain name example.com from the set of possible subdomains sub1.example.com sub2.example.com sub3.example.com using javascript ...?
var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');
To get only the second-level-domain, you might use
var parts = location.hostname.split('.');
var sndleveldomain = parts.slice(-2).join('.');
The accepted answer will work to get the second level domain. However, there is something called "public suffixes" that you may want to take into account. Otherwise, you may get unexpected and erroneous results.
For example, take the domain www.amazon.co.uk.
If you just try getting the second level domain, you'll end up with co.uk, which is probably not what you want. That's because co.uk is a "public suffix", which means it's essentially a top level domain. Here's the definition of a public suffix, taken from https://publicsuffix.org:
A "public suffix" is one under which Internet users can (or historically could) directly register names.
If this is a crucial part of your application, I would look into something like psl (https://github.com/lupomontero/psl) for domain parsing. It works in nodejs and the browser, and it's tested on Mozilla's maintained public suffix list.
Here's a quick example from their README:
var psl = require('psl');
// TLD with some 2-level rules.
psl.get('uk.com'); // null);
psl.get('example.uk.com'); // 'example.uk.com');
psl.get('b.example.uk.com'); // 'example.uk.com');
This is faster
const firstDotIndex = subDomain.indexOf('.');
const domain = subDomain.substring(firstDotIndex + 1);
The generic solution is explained here http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain
From above link
var domain = (function(){
var i=0,domain=document.domain,p=domain.split('.'),s='_gd'+(new Date()).getTime();
while(i<(p.length-1) && document.cookie.indexOf(s+'='+s)==-1){
domain = p.slice(-1-(++i)).join('.');
document.cookie = s+"="+s+";domain="+domain+";";
}
document.cookie = s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";
return domain;
})();
function getDomain() {
const hostnameArray = window.location.hostname.split('.')
const numberOfSubdomains = hostnameArray.length - 2
return hostnameArray.length === 2 ? window.location.hostname : hostnameArray.slice(numberOfSubdomains).join('.')
}
console.log(getDomain());
This will remove all subdomains, so "a.b.c.d.test.com" will become "test.com"
If you want to verify if a specific subdomain exists
var parts = location.hostname.split('.');
if(parts.includes('subdomain_to_search_here')){
//yes
}else{
//no
}
some more robust version, which is independent of the subdomain count
function getDomain() {
const hostname = window.location.hostname.split('.');
hostname.reverse();
return `${hostname[1]}.${hostname[0]}`;
}
Related
I'm looking for the simplest way to check if the user is on the normal domain (domain.com) or is on a subdomain et.domain.com and display content based on that. If it matters I'm trying to do that on shopify.
You can split the url with dot(.) and check the length. This will only work for .com url.
Note: This will not work for domains like google.co.in
const domain = 'domain.com';
const subDomain = 'et.domain.com'
const isSubdomain = (domain) => domain.split('.').length > 2;
console.log(isSubdomain(domain));
console.log(isSubdomain(subDomain));
You can actually use regex method.
var isSubdomain = function(url) {
url = url || 'http://www.test-domain.com'; // just for the example
var regex = new RegExp(/^([a-z]+\:\/{2})?([\w-]+\.[\w-]+\.\w+)$/);
return !!url.match(regex); // make sure it returns boolean
}
console.log(isSubdomain("example.com"));
console.log(isSubdomain("http://example.com:4000"));
console.log(isSubdomain("www.example.com:4000"));
console.log(isSubdomain("https://www.example.com"));
console.log(isSubdomain("sub.example.com"));
console.log(isSubdomain("example.co.uk")); //it doesn't work on these very specific cases
I try to set a cookies via js using jQuery.cookie for all the current subdomains like this
$.cookie('account', 'myvalue', { path: '/', domain: '.domain.com' });
The thing is that window.location.hostname will return www.domain.com or domain.com depending on its context.
Is there any method available to simply replace the subdomain if present to a "." and if no subdomain present still show the . at the beginning?
For any of the following values:
any.number.of.host.names.here.foo.domain.com
foo.domain.com
domain.com
the following will work:
"." + window.location.hostname.split('.').slice(-2).join('.');
A host of localhost would return .localhost in this case. I'm not entirely sure of the best behavior in that respect. See: Cookies on localhost with explicit domain
If you need to look out for IP addresses as a hostname, you''ll want to add a bit more logic to determine if it's an IP address.
A better approach might be:
function getDomain() {
var path = window.location.hostname.split('.');
// See above comment for best behavior...
if(path.length === 1) return window.location.hostname;
if(path.length === 4 && isIPAddress(path)) return window.location.hostname;
return "." + window.location.hostname.split('.').slice(-2).join('.');
}
// doesn't check for ip V6
function isIPAddress(path) {
for(var i = 0; i < path.length; ++i) {
if(path[i] < 0 || path[i] > 255) {
return false;
}
}
return true;
}
Important
As #Hiroto noted in one of the comments, make sure you know which domain(s) this logic will be used on. It wouldn't be a good idea to set cookies for .co.uk. For an interesting read on this problem see: Mozilla Bug 252342: fix cookie domain checks to not allow .co.uk
The question asked "what is the quickest way", so this is the quickest way because it uses the least lines of code and does not add the overhead of the context switch that JavaScript has for functions, or a for loop:
var domain = window.location.hostname;
var parts = domain.split('.');
var isIpAddress;
// Decide whether host is IP address
isIpAddress = /[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}/.test(domain);
// If it's an IP, then use full host name,
// otherwise just use last two values of the dot-delimited host name array
if(isIpAddress)
domain = window.location.hostname;
else
{
if(parts.length <= 3)
domain = '.'+window.location.hostname;
else
domain = '.'+window.location.hostname.split('.').slice(1).join('.');
}
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 detect the actual domain name that the page is loading from so that I know what to change my content to?
I've looked around for stuff like this but most of it doesn't work the way I want it to.
For instance when using
document.write(document.location)
on JSFiddle it returns
http://fiddle.jshell.net/_display/
i.e. the actual path or whatever that is.
How about:
window.location.hostname
The location object actually has a number of attributes referring to different parts of the URL
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
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"
Now we can conclude you're looking for:
window.location.hostname
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);
}
function getDomain(url, subdomain) {
subdomain = subdomain || false;
url = url.replace(/(https?:\/\/)?(www.)?/i, '');
if (!subdomain) {
url = url.split('.');
url = url.slice(url.length - 2).join('.');
}
if (url.indexOf('/') !== -1) {
return url.split('/')[0];
}
return url;
}
Examples
getDomain('http://www.example.com'); // example.com
getDomain('www.example.com'); // example.com
getDomain('http://blog.example.com', true); // blog.example.com
getDomain(location.href); // ..
Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'
If you wish a full domain origin, you can use this:
document.location.origin
And if you wish to get only the domain, use can you just this:
document.location.hostname
But you have other options, take a look at the properties in:
document.location
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"
window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.
There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:
let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?([a-zA-Z0-9\-_]{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
Since this question asks for domain name, not host name, a correct answer should be
window.location.hostname.split('.').slice(-2).join('.')
This works for host names like www.example.com too.
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
http://jsfiddle.net/5U366/4/
Use
document.write(document.location.hostname)
window.location has a bunch of properties. See here for a list of them.
I figure it ought to be as simple as this:
url.split("/")[2]
If you want to get domain name in JavaScript, just use the following code:
var domain_name = document.location.hostname;
alert(domain_name);
If you need to web page URL path so you can access web URL path use this example:
var url = document.URL;
alert(url);
What about this function?
window.location.hostname.match(/\w*\.\w*$/gi)[0]
This will match only the domain name regardless if its a subdomain or a main domain
for my case the best match is window.location.origin
Combining a few answers from the above, the following works really well for me for destroying Cookies:
/**
* Utility method to obtain the domain URI:
*/
fetchDomainURI() {
if (window.location.port.length > 0) {
return window.location.hostname;
}
return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
}
Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.
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.
Even if the question is about the domain name, the accepted solution includes the subdomain (eg. you get blog.example.com calling location.hostname).
For future reference I suggest a one-liner to extract only the domain (eg. https://blog.example.com/index.html -> example.com) as Micheal.
location.hostname.split('.').filter(( _, i) => i < 2).join('.')
Beware! It can break when the TLD is composed of two parts (eg. .co.uk). If that's your case change 2 with 3 in the code above.
you can use this to do away with the port number.
var hostname = window.location.host;
var urlWithoutPort = `https://${hostname}`;
console.log(urlWithoutPort);
https://publicsuffix.org/list/
(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)
is needed to correctly parse out all domains without suffixes, working with dots as in the answers above will never completely be correct. Feel free to run the above codes samples against the public suffixes dat file to realize this.
You can roll your own code based on this or use a package like https://www.npmjs.com/package/tldts
getDomainWithoutSuffix('google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.google'); // returns `google`
getDomainWithoutSuffix('foo.google.co.uk'); // returns `google`
getDomainWithoutSuffix('t.co'); // returns `t`
getDomainWithoutSuffix('fr.t.co'); // returns `t`
getDomainWithoutSuffix('https://user:password#example.co.uk:8080/some/path?and&query#hash'); // returns `example`
<script src="myscript.js?someParameter=123"></script>
From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?
Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.
There are two ways to pass parameters to another JavaScript file:
As #Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.
Jquery Address does this, so i've been checking their code out and this is the improved solution I just created myself:
$.each($('script'), function(id, val){ //loop trough all script-elements
var tmp_src = String($(this).attr('src'));//store the src-attr
var qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index
//Check if the script is the script we are looking for and if it has QS-params
if(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
{
//this is myscript.js and has a querystring
//we want an array of param-pairs: var1 = value1, var2 = value2, ...
var params_raw = tmp_src.substr(qs_index + 1).split('&');
//create empty options array
var options = [];
//loop troug raw params
$.each(params_raw, function(id, param_pair){
//split names from values
var pp_raw = param_pair.split('=');
//store in options array
options[pp_raw[0]] = pp_raw[1];
});
//check the results out in the console!
console.log(options);
}
});
I hope this does what you need?
The answer is a definite "YES". I've been doing this on various projects for over a decade. The solution is actually easy, it's just non-intuitive (you have to generate an error). To be clear, the following code lets you do something like this:
<script src="https://example.com/script.js?id=1&bar=this works!" />
All you need to do is initiate a silent error, which takes less than 1/1000 of a second even on the worst outdated mobile browsers. You shouldn't do it a ton, but you only need to do it once. This error is processed, so it won't show up as an error in telemetry or 3rd party error trackers either.
// Generic function used to see if a param exists in a URL string.
// Provided here in case you don't know how to do it.
// This is not needed for the solution.
function getParameter (name, url) {
if (!url) url = scriptName()
name = name.replace(/[\[\]]/g, '\\$&')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
var results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
// Gets the name of this script (whatever this file runs in)
// You can use this name to get parameters just like you would for the window URL :)
function getScriptName () {
var error = new Error(),
source,
lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/),
currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/)
if ((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] !== '')
return source[1]
else if ((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1]
else if (error.fileName !== undefined)
return error.fileName
}
If I have a hostname such as: http://sample.example.com and in Javascript I do window.location.hostname, would I get "example.com" or "sample.example.com"?
If not, how would I be able to get sample.example.com?
Yes, window.location.hostname will give you subdomains as well. If this isn't working, or isn't supported by some other browser, you could quite easily parse for it:
// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
This does the trick for me:
var host = window.location.host
var subdomain = host.split('.')[0]
I know this is an old question but a more robust answer would be to capture all subdomains. It's possible to have nested subdomains such as https://my.company.website.com. In order to adequately capture all subdomains, I think this is the simplest answer:
// for https://my.company.website.com,
const subdomain = window.location.hostname.split('.').slice(0, -2).join('.');
console.log(subdomain); // "my.company"
It can be done as below:
var subdomain = window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;
First of all, it's window.location, not document.location (document.location works in some browsers but it is not standard)
And yes, location.hostname will return the entire domain name, including any subdomains
Read more here
Window Location
const subdomain = window.location.hostname.split(".")[0]
window.location.hostname return string include subdomain - main domain - ltd
so you can easily get the first word by converting it to an array then getting first item
Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.
How about this snippet. It might help:
var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);
with array destructuring you can do this:
// window.location.host = "meta.stackoverflow.com"
const [ , , subdomain] = window.location.hostname.split(".").reverse();
// console.log(subdomain);
// "meta"
I recommend using the npm package psl (Public Suffix List). You can look this link: npm psl
It's a simple way to split domain parts like subdomain.maindomain.extension
// Print Subdomain
console.log(window.location.host.split('.')[0]);
// Print Maindomain
console.log(window.location.host.split('.')[1]);
// Print extension
console.log(window.location.host.split('.')[2]);
I recommend you reference this helpful cheatsheet.
source: https://www.samanthaming.com/tidbits/86-window-location-cheatsheet/