0

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.

Ron
  • 15
  • 6
  • I suggest you take a look on this: https://stackoverflow.com/questions/7930751/regexp-for-subdomain/7933253 – mtz1406 Dec 29 '21 at 11:22

2 Answers2

1

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));
  • Interesting. The user can be on www.domain.com as well as domain.com or et.domain.com. Only the last one should be 'true'. Any thoughts? – Ron Dec 29 '21 at 11:40
  • `console.log(domain.includes('et.')); ` I like this solution. Seems to work – Ron Dec 29 '21 at 11:44
0

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
Onkar Kole
  • 1,197
  • 7
  • 13
  • I saw this solution but it returns 'true' for https://www.example.com and sub.example.com. It should not contain www as a subdomain... – Ron Dec 29 '21 at 11:34