skip to Main Content

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.

2

Answers


  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));
    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search