简体   繁体   中英

Simplest way to check if the current url contains a subdomain

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(/^([az]+\:\/{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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM